-
Notifications
You must be signed in to change notification settings - Fork 198
Closed
Description
Hey! Awesome work with this project and it's been massively helpful :)
Could it be possible to define a type schema from a TypeScript type predicate?
Something like this is what I have in mind, I'm curious if there's a way to achieve this now or what you think about adding it to TypeBox (I'd be happy to create a PR).
// type predicate (https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards)
export function isMyType(value: unknown): value is MyType {
return typeof value === "number" && Number.isInteger(value) && value >= 0
// ...or some other custom type-checking logic
}
// tagged intersection (https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#type-aliases)
export type MyType = number & { __myType: never }
// defining a schema based off the predicate (the type is inferred to be TPredicate<MyType>)
const MyTypeSchema = Type.Predicate(isMyType)And potential signatures:
export interface TPredicate<T> extends TSchema {
[Kind]: 'Predicate'
static: T
// maybe some others...?
}
// Type.Predicate(...) schema function
export function Predicate<T>(
predicate: (value: unknown) => value is T,
options: SchemaOptions = {},
): TPredicate<T> {
// ...
}Metadata
Metadata
Assignees
Labels
No labels