Created
April 26, 2021 16:04
-
-
Save smbkr/c2d17cf41e95551b118d213606848660 to your computer and use it in GitHub Desktop.
TypeScript utility types
This file contains 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 type Primitive<T> = T extends string | |
? string | |
: T extends number | |
? number | |
: T extends boolean | |
? boolean | |
: T extends Record<keyof any, unknown> | |
? Lookalike<T> | |
: never; | |
export type Lookalike<T> = { | |
[K in keyof T]: Primitive<T[K]>; | |
}; | |
// eg. | |
const config = { | |
dbName: 'foo', | |
collectionName: 'bar', | |
} as const; // note this is a const literal | |
// illegal | |
config.dbName = 'changed'; | |
// illegal | |
const fake: typeof config = { | |
dbName: 'baz', | |
collectionName: 'bat', | |
}; | |
// permitted | |
const testConfig: Lookalike<typeof config> = { | |
dbName: 'bob', | |
collectionName: 'belcher', | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment