Slide 1

Slide 1 text

Keep alive your typescript definitions using Zod Luca Del Puppo

Slide 2

Slide 2 text

Who I am Luca Del Puppo 
 (aka Puppo) 
 Full-Stack Developer @ Flowing a Claranet Company 
 and Microsoft MVP @puppo92 
 https://www.linkedin.com/in/lucadelpuppo/ 
 [email protected]

Slide 3

Slide 3 text

Typescript journey 1

Slide 4

Slide 4 text

10 years ago

Slide 5

Slide 5 text

The developers reaction

Slide 6

Slide 6 text

interface CustomerModel { id: number; name: string; email: string; phone: string; } Interfaces

Slide 7

Slide 7 text

type CustomerModel = { id: number; name: string; email: string; phone: string; }; Types

Slide 8

Slide 8 text

HTTP Request

Slide 9

Slide 9 text

But after a while…

Slide 10

Slide 10 text

➔ Typescript enables type check but on BUILT - TIME ➔ After the build all your types disappears ➔ After the build all your considerations about types dissolve Why?

Slide 11

Slide 11 text

Prevent ugly mistakes 2

Slide 12

Slide 12 text

Zod is your super hero

Slide 13

Slide 13 text

import { z } from ‘zod’; const CustomerSchema = z.object({ id: z.number(), name: z.string(), email: z.string(), phone: z.string(), }); Schema

Slide 14

Slide 14 text

import { TypeOf } from ‘zod'; type CustomerModel = TypeOf; Convert to type

Slide 15

Slide 15 text

const res = CustomerSchema.parse({ id: 1, name: 'John Doe', email: '[email protected]', phone: '555-555-5555' }); Parse method

Slide 16

Slide 16 text

➔ Parse throws an Error ➔ ZodError is the right error to check ➔ ZodError contains all the issues that describe the errors Something wrong?

Slide 17

Slide 17 text

Do you hate exceptions? use safeParse

Slide 18

Slide 18 text

safeParse Success ➔ success: true ➔ data: Output Error ➔ success: false ➔ error: ZodError

Slide 19

Slide 19 text

Benefits of using Zod

Slide 20

Slide 20 text

Create a layer between your app and the outside V a l i d a t i o n HTTP socket.io

Slide 21

Slide 21 text

Demo 3

Slide 22

Slide 22 text

Conclusion 4

Slide 23

Slide 23 text

➔ Typescript is awesome, but it’s good only on built time ➔ Create a validation layer between your app and the outside • Prevent execution of code with wrong data • You can get notifications if something is changed ➔ Using Zod, you can guarantee your types, both built-time and run-time Conclusion

Slide 24

Slide 24 text

CODE SLIDE

Slide 25

Slide 25 text

Thanks! That’s All! Luca Del Puppo @puppo92 
 https://www.linkedin.com/in/lucadelpuppo/ 
 [email protected]