Skip to content

Instantly share code, notes, and snippets.

@pixleight
Created October 14, 2021 18:50
Show Gist options
  • Save pixleight/9bfaf6386b7034080e888743278c14f8 to your computer and use it in GitHub Desktop.
Save pixleight/9bfaf6386b7034080e888743278c14f8 to your computer and use it in GitHub Desktop.
Method for typing objects with allowed keys
// 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