Skip to content

Commit

Permalink
docs: added infer-types guide
Browse files Browse the repository at this point in the history
  • Loading branch information
mahabubx7 committed Oct 16, 2024
1 parent 2197438 commit 8497c58
Showing 1 changed file with 72 additions and 12 deletions.
84 changes: 72 additions & 12 deletions docs/guide/infer-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,84 @@ While working in TypeScript, we often need to use types for various usages. Our

## Infer Schema

:::info
We are wotking on it.
:::
```TypeScript
import { a, InferSchema } from 'akarjs'

// Sample | for example, an object-schema
const createTodo = a.object({
title: a.string().min(3),
completed: a.boolean().optional(),
})

type CreateTodo = InferSchema<typeof createTodo>

/*
/// Infers as:
type CreateTodo {
title: string;
completed: boolean | undefined;
}
*/

```

## Infer Schema With Conditions

:::info
We are wotking on it.
:::
```TypeScript
import { a, InferSchemaWithConditions } from 'akarjs'

// conditional for types
const updateUser = a.object({
name: a.string().min(3),
age: a.number().optional(),
role: a.enum(['customer', 'vendor'] as const).optional(),
})

type UpdateUser = InferSchemaWithConditions<typeof updateUser>

/*
/// Infers as:
type UpdateUser {
name: string;
} & {
age?: number;
} & {
role?: 'customer' | 'vendor';
}
*/

```

## Why Conditional Types?

:::info
We are wotking on it.
:::
We have noticed that when you infer a type and try to use it, you might face a problem. For example,

```TypeScript
const updateUser = a.object({
name: a.string().min(3),
age: a.number().optional(),
role: a.enum(['customer', 'vendor'] as const).optional(),
})

type UpdateUserT1 = InferSchema<typeof updateUser>
type UpdateUserT2 = InferSchemaWithConditions<typeof updateUser>

const user1: UpdateUserT1 = {
name: "Mahabub",
age: undefined, // property must be declared, otherwise it might make problems
role: undefined, // property must be declared, otherwise it might make problems
};

const user2: UpdateUserT2 = {
name: "Mahabub",
// no need to add optional properties
// Enjoy 👍
};

```

## Conclusion

:::info
We are wotking on it.
:::
In conclusion, leveraging the power of TypeScript with our library allows for robust type inference directly from your schemas. This not only ensures type safety but also enhances code maintainability and readability. By using conditional types, you can further refine your type definitions, making your code more flexible and easier to work with. We hope this guide helps you understand how to effectively use inferred types in your projects.

0 comments on commit 8497c58

Please sign in to comment.