Created
October 15, 2017 08:56
-
-
Save skyjur/0ab9ae07ee28f5a1b00d2b1f67ece05d to your computer and use it in GitHub Desktop.
schema to static magic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"]] | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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