I have an object with defined type for value:
type Type = { [key: string]: ValueType }
const variable: Type = {
key1: valueType,
key2: valueType,
key3: valueType,
}
And I have a function func, which I want to be accepting only string with values from variable's keys:
func('key1') // OK
func('key2') // OK
func('key3') // OK
func('keyother') // Error
func(3) // Error
And this is what I have done when making type for func:
type FuncType = (param: keyof typeof variable) => any
const func: FuncType = ...
But I can only achieve one:
- typing for
variable's value
or
- typing for
func'sparamaccept onlyvariable's key
Not both.
- If I'm typing for
variable's valueconst variable: Type = {,paramhasstringtype and I can pass any string tofunccall, which is wrong - If I'm not typing for
variable's valueconst variable: Type = {,funcnow typingparamcorrectly but it makesvariableaccept anything as value.
Another way I can think about is predefined Type with list of keys ([key1, key2, ...]). But I don't want to maintain two list of the same thing. How can I achieve both of them without doing this way.
Typescript playground for this problem, which has some comments to describe problem more clearfully.