How do I make a generic that takes a TSchema or undefined and if undefined returns TUnknown while still retaining type inference?
#424
Replies: 2 comments 8 replies
-
|
@jessekrubin Hi! Unfortunately, there's not really an ideal way to define optional arguments for generic types. The problem with optionals is that The following implements some conditional types to map for the import { Type, TSchema, TObject, AssertType } from '@sinclair/typebox'
type IsDefined<T> = Extract<T, undefined> extends never ? true : false
type TMake<T extends TSchema | undefined> = IsDefined<T> extends true
? TObject<{ x: AssertType<T> }>
: TObject<{}>
const Make = <T extends TSchema | undefined>(schema?: T) => {
return (schema !== undefined
? Type.Object({ x: schema })
: Type.Object({ })
) as TMake<T>
}
const A = Make(Type.String()) // TObject<{ x: TString; }>
const B = Make() // TObject<{ }>Hopefully you can update the above for your use case! |
Beta Was this translation helpful? Give feedback.
-
|
@sinclairzx81 I just made public the package/code I have been fiddling with in my spare time (https://github.com/jessekrubin/geobox) and I am trying to figure out an elegant way of being able to hand the feature-schema-creating-function (eg: Ideally if no schema is provided as an option to the function ( This is in no way pressing, just curious if you have any thoughts! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I am trying to write a generic function that takes a
TSchemaparamconst makeSchema = <T extends TSchema>(schema?: T)but returnsTUnknownif the schema given is undefined. Maybe this is a dumb question, but I am confused!Beta Was this translation helpful? Give feedback.
All reactions