Ensuring adherence to existing TypeScript interface #449
-
Hi all I've tried to find the answer to this question myself, but no luck. Is there a utility type in TypeBox that will let me check a schema's adherence to an exiting type. Something like Superstruct's
Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
@sdc395 Hi, Sorry for the delay in reply on this one (I must have missed this question). TypeBox doesn't have a import { Type, TObject, TString, TNumber } from '@sinclair/typebox'
const user: TObject<{
name: TString,
age: TNumber
}> = Type.Object({
name: Type.String(),
age: Type.Number(),
}) Additionally, it's possible to implement import { TObject, TString, TNumber, TBoolean, TUnknown } from '@sinclair/typebox'
export type Describe<T> =
T extends Record<any, unknown> ? TObject<{ [K in keyof T]: Describe<T[K]> }> :
T extends string ? TString :
T extends number ? TNumber :
T extends boolean ? TBoolean :
TUnknown
type TUser = Describe<{ // hover TUser
name: string
age: number
}> Conditional mapping arrays, tuples, unions, intersections and other constructs is an exercise ill leave for you. Hope this helps! |
Beta Was this translation helpful? Give feedback.
@sdc395 Hi,
Sorry for the delay in reply on this one (I must have missed this question). TypeBox doesn't have a
Describe<T>
utility type built in, but it does have types to express each schematic. By convention, TypeBox types are prefixed withT
, so you can enforce structures in the following way.Additionally, it's possible to implement
Describe<T>
through conditional mapping. The following is one way you can achieve this.TypeScript Link Here