Skip to content

Instantly share code, notes, and snippets.

@ChuckJonas
Created May 8, 2021 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChuckJonas/974f08b77222b47a1e1c956286010f12 to your computer and use it in GitHub Desktop.
Save ChuckJonas/974f08b77222b47a1e1c956286010f12 to your computer and use it in GitHub Desktop.
Typescript Examples
const schema = {
uploadDocToValt: { type: 'string' },
foo: { type: 'boolean' },
inner: { type: 'object', object: {
test: {type: 'number'},
innerinner: {type: 'object', object: {
woweee: {type: 'string[]'},
}}
}}
} as const;
type ObjectType = {type: 'object', object: TypedObject};
type Type = {type: 'string' | 'boolean' | 'number' | 'string[]'};
type TypedObject = {[key: string] : ObjectType | Type}
type SchemaInstance<T extends TypedObject> = {
[Property in keyof T]:
T[Property] extends ObjectType ? SchemaInstance<T[Property]['object']> :
LiteralToType<T[Property]>
};
type LiteralToType<T extends ObjectType | Type> =
T['type'] extends 'string' ? string:
T['type'] extends 'boolean' ? boolean :
T['type'] extends 'number' ? number :
T['type'] extends 'string[]' ? string[] :
never;
declare const x: SchemaInstance<typeof schema>;
x.inner.innerinner.woweee // string[]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment