Created
August 25, 2017 08:37
-
-
Save JakeSidSmith/cd0d86e77a701e1120905b37c947c9e8 to your computer and use it in GitHub Desktop.
TypeScript exact key value mappings
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
/* 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