Skip to content

Instantly share code, notes, and snippets.

@JakeSidSmith
Created August 25, 2017 08:37
Show Gist options
  • Save JakeSidSmith/cd0d86e77a701e1120905b37c947c9e8 to your computer and use it in GitHub Desktop.
Save JakeSidSmith/cd0d86e77a701e1120905b37c947c9e8 to your computer and use it in GitHub Desktop.
TypeScript exact key value mappings
/* Tested with TypeScript 2.4.2 */
// If you create an object like this, although the keys are correctly inferred, all of the values will be of type string
const obj = {
FOO: 'FOO', // FOO: string
BAR: 'BAR', // BAR: string
};
// You can easily fix this by defining a type for the key values
type KeyValue = 'FOO' | 'BAR';
// You can then use this to define the exact keys and values in an object
const exactObj: {[K in KeyValue]: K} = {
FOO: 'FOO', // FOO: 'FOO'
BAR: 'BAR', // BAR: 'BAR'
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment