I am attempting to create a localized strings object:
const strings = {
hello: {
en: 'hello',
pl: 'hej'
},
bye: {
en: 'bye',
pl: 'pa'
}
}
While this setup works and Intellisense shows available options like hello
and bye
, it does not enforce strict typing. Some properties may be missing the en
or pl
keys, or even have additional keys that should not exist. To make the object more specific, I used an enum and typed the object:
enum Language {
en = 'en',
pl = 'pl'
}
type Strings = { [k: string]: { [lang in Language]: string } }
const strings: Strings = {
// ...same as before
}
Now, my strings
properties are properly typed. However, there is a trade-off as now the properties lose their explicit typings due to [k: string]
. This means that accessing strings.dontExist
will not throw an error.
So, my question is how can I have inferred properties (like in the initial example) while also having strongly typed properties explicitly set by me ({ [lang in Language]: string }
)?
[using typescript 3.6.2]