diff --git a/README.md b/README.md index 43ffb9c..1afe317 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1232 TILs and counting..._ +_1233 TILs and counting..._ --- @@ -1136,6 +1136,7 @@ _1232 TILs and counting..._ - [Compiler Checks For Unused Params And Variables](typescript/compiler-checks-for-unused-params-and-variables.md) - [Extract Object Type Keys Into A Union Type](typescript/extract-object-type-keys-into-a-union-type.md) - [Extract Object Type Values Into A Union Type](typescript/extract-object-type-values-into-a-union-type.md) +- [Generate Inferred Type From Zod Schema](typescript/generate-inferred-type-from-zod-schema.md) - [Interfaces With The Same Name Are Merged](typescript/interfaces-with-the-same-name-are-merged.md) - [Re-Export An Imported Type](typescript/re-export-an-imported-type.md) - [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md) diff --git a/typescript/generate-inferred-type-from-zod-schema.md b/typescript/generate-inferred-type-from-zod-schema.md new file mode 100644 index 0000000..3f0f5fa --- /dev/null +++ b/typescript/generate-inferred-type-from-zod-schema.md @@ -0,0 +1,56 @@ +# Generate Inferred Type From Zod Schema + +One of the killer features of [`Zod`](https://github.com/colinhacks/zod) is +that it does double-duty. When you define a schema, you can use that for +runtime checks. You can also generate an inferred type from that schema for +static type checking. + +Let's say I have the following schema defined for data representing a +_contact_. + +```typescript +import {z} from 'zod' + +const contactSchema = z.object({ + person: z.object({ + firstName: z.string(), + lastName: z.string() + }), + email: z.string().email(), +}) +``` + +I can use this schema along with Zod's +[`z.infer()`](https://github.com/colinhacks/zod#type-inference) function to +generate a type that I can use throughout my codebase. + +```typescript +const createContact = (data: z.infer) => { + // ... +} +``` + +If I inspect data, I can see that I get an object type generated from the +`contactSchema`. + +```typescript +/* data: { + * person: { + * firstName: string; + * lastName: string; + * }; + * email: string; + * } + */ +``` + +That works, but looks a bit cluttered. I could pull it out into a defined type. +One that could even be exported if I was so inclined. + +```typescript +export type Contact = z.infer + +const createContact = (data: Contact) => { + // ... +} +```