Skip to content

Instantly share code, notes, and snippets.

@smbkr
Created April 26, 2021 16:04
Show Gist options
  • Save smbkr/c2d17cf41e95551b118d213606848660 to your computer and use it in GitHub Desktop.
Save smbkr/c2d17cf41e95551b118d213606848660 to your computer and use it in GitHub Desktop.
TypeScript utility types
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