Created
October 14, 2021 18:50
-
-
Save pixleight/9bfaf6386b7034080e888743278c14f8 to your computer and use it in GitHub Desktop.
Method for typing objects with allowed keys
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
// Instead of typing an object like this: | |
interface Person { | |
[key: string]: unknown | |
} | |
// Only allow certain keys | |
type AllowedKeys = 'name' | 'age'; | |
type StrictPerson = Record<AllowedKeys, unknown>; | |
/** | |
equivalent to: | |
interface StrictPerson { | |
name: unknown | |
age: unknown | |
} | |
*/ | |
// If later more keys are added to `AllowedKeys`, these typed objects will throw an error | |
const Human: StrictPerson = { | |
name: 'Chris', | |
age: 36, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment