I have the following (almost) JavaScript code that works as intended:
const config = {
a: 1,
b: 2,
default: 3
}
const getConfig = (key: string) => {
return config[key] || config.default
}
However, in TypeScript gives me of course an error, because not any kind of string is a valid index of config.
But the following unfortunately doesn't work either:
const getConfig = (key: string) => {
return key in config
? config[key]
: config.default
}
Is there a way to construct some kind of type predicate or what would you recommend? Do I really have to do config as any? That would seem silly...