Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: add generic type to parse (#133)
Given the following code: ```ts /** * Removes `null`, `undefined` and `?` from an object * This essentially combines `Required<T>`, * `NonNullable<T>` and `NonUndefined<T>` */ type NonNullish<T> = { [P in keyof T]-?: Exclude<T[P], undefined | null>; }; /** * Type union for the full 2 billion dollar mistake in the JavaScript ecosystem */ type Nullish = null | undefined; interface MyArgs { offset: number | Nullish; take: number | Nullish; } /** * Validate the schema * * Note: After calling `parse` the values will never be * `null` or `undefined` because of the nullish coalescing. */ const schema: SchemaOf<MyArgs> = s.object({ offset: s.number.greaterThanOrEqual(0).nullish.transform((v) => v ?? 0), take: s.number .greaterThanOrEqual(1) .lessThanOrEqual(50) .nullish.transform((v) => v ?? 1), }); /** * Validates and transforms the args */ function validate(args: MyArgs): NonNullish<MyArgs> { return schema.parse(args); } ``` This would previously give an error on `validate`: ```ts Type 'MyArgs' is not assignable to type 'NonNullish<MyArgs>'. Types of property 'offset' are incompatible. Type 'number | Nullish' is not assignable to type 'number'. Type 'undefined' is not assignable to type 'number'. ts(2322) ```
- Loading branch information