LoginSignup
4
0

More than 1 year has passed since last update.

ZodでGenericsを使った型定義をする

Last updated at Posted at 2022-12-29

概要

下のようにGenericsを使った型定義を使うことがありますね。

Genericsを使った型定義
type AnyRecord = { [key: string]: any };
type WithProps<P extends AnyRecord> = {
  props: { name: string } | P;
};
Genericsを使った型定義を利用する
type WithId = AddProps<{ id: number }>;

// type WithId = {
//   props:
//     | {
//         id: number;
//       }
//     | {
//         name: string;
//       };
// };

同様のSchemaをZodで定義することができます。

ZodでGenericsを使った型定義
const anyRecord = z.record(z.any());
type AnyRecord = z.infer<typeof anyRecord>;

const withProps = <T extends z.ZodType<AnyRecord>>(schema: T) =>
  z.object({
    props: z.union([z.object({ name: z.string() }), schema])
  });
type WithProps = z.infer<typeof withProps>;
ZodでGenericsを使った型定義を利用する
const withId = withProps(z.object({ id: z.number() }));
type WithId = z.infer<typeof withId>;

// type WithId = {
//   props:
//     | {
//         id: number;
//       }
//     | {
//         name: string;
//       };
// };

参考

4
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
4
0