Skip to content

Instantly share code, notes, and snippets.

@skyjur
Created October 15, 2017 08:56
Show Gist options
  • Select an option

  • Save skyjur/386ee830afb35083250f999f66082f9d to your computer and use it in GitHub Desktop.

Select an option

Save skyjur/386ee830afb35083250f999f66082f9d to your computer and use it in GitHub Desktop.
schema to static magic
export const tString : 'string' = 'string';
export const tNumber : 'number' = 'number';
export interface TypeMap {
'number': number;
'string': string
}
export type Schema = {
[fieldName: string]: {type: "string" | "number"}
}
export type Static<T extends Schema> = {
[fieldName in keyof T]: TypeMap[T[fieldName]["type"]]
}
improt { Schema, Static, tString, tNumber } from './schema.ts';
const User = {
id: {type: tNumber},
username: {type: tString}
}
type UserType = Static<typeof User>;
let user1 : UserType = {
id: 123,
username: "abc" // all good
// <ctrl+space> autocompletion provides "id" and "username" options
}
let user2 : UserType = {
id: 'abc',
username: 123
// [ts]
// Type '{ id: string; username: number; }' is not assignable to type 'Static<{ id: { type: "number"; }; username: { type: "string"; }; }>'.
// Types of property 'id' are incompatible.
// Type 'string' is not assignable to type 'number'.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment