LoginSignup
3
0

More than 1 year has passed since last update.

Zodで、Genericsで渡したスキーマから型定義を生成する

Posted at

スキーマから型定義を生成する

ご存知の通り、Zodではz.infer<T>でスキーマから型定義を生成できます。

const StudentSchema = z.object({ name: z.string(), age: z.number() });
type StudentType = z.infer<typeof StudentSchema>;
// StudentType = { name: string; age: number; }

Genericsで渡したスキーマから型定義を生成する

スキーマをGenericsで渡して、渡したスキーマから型定義を生成したい場合、Genericsの型にextends ZodTypeAnyの制約を加えてあげればOKです。

const validate = <TSchema extends ZodTypeAny>(input: unknown, schema: TSchema): z.infer<TSchema> => 
{
	return schema.parse(input);
}

const StudentSchema = z.object({ name: z.string(), age: z.number() });
const student = validate({ name: 'foo', age: 18}, StudentSchema);
// typeof student = { name: string; age: number; }

参考

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0