%% generate tags start %%
#software-engineering
%% generate tags end %%
#software-engineering/typescript
static typecheck is done by typecheck. But after compilation, typescript is transpiled to javascript and there is no more typecheck. We can do runtime typecheck by zod.
> [!info]
> Here I introduce 3 packages. Most of the time, zod is enough. Doc is the best for zod.
## Zod
> [!info] see more
> [colinhacks/zod: TypeScript-first schema validation with static type inference (github.com)](https://github.com/colinhacks/zod)
zod is mostly used to construct schema. Then you use the function `parse` to check if the object has the correct shape using `parse`. If not, it will throw error.
```ts
import { z } from "zod";
// creating a schema for strings
const mySchema = z.string();
// parsing
mySchema.parse("tuna"); // => "tuna"
mySchema.parse(12); // => throws ZodError
// "safe" parsing (doesn't throw error if validation fails)
mySchema.safeParse("tuna"); // => { success: true; data: "tuna" }
mySchema.safeParse(12); // => { success: false; error: ZodError }
```
```ts
import { z } from "zod";
const User = z.object({
username: z.string(),
});
User.parse({ username: "Ludwig" });
// extract the inferred type
type User = z.infer<typeof User>;
// { username: string }
```
Most of the time, we don't need to use zod alone. zod is usually used with other integration. For example, trpc use zod to validate api input and output. Therefore, we just need to focus on how to write good schema.
## Valibot
[fabian-hiller/valibot: The modular and type safe schema library for validating structural data 🤖 (github.com)](https://github.com/fabian-hiller/valibot)
## Typebox
checkout: [[Json to type | typebox]]
## Typia
[Typia Guide Documents - Pure TypeScript](https://typia.io/docs/pure/#demonstration)
Runtime validation with pure typescript ??? 🤯
## Arktype
[arktypeio/arktype: TypeScript's 1:1 validator, optimized from editor to runtime (github.com)](https://github.com/arktypeio/arktype)
ArkType is a runtime validation library that can infer **TypeScript definitions 1:1** and reuse them as **highly-optimized validators** for your data.