I have an object with specific types for its values:
type Type = { [key: string]: ValueType }
const variable: Type = {
key1: valueType,
key2: valueType,
key3: valueType,
}
Now, I need a function called func
that should only accept keys from variable
:
func('key1') // OK
func('key2') // OK
func('key3') // OK
func('keyother') // Error
func(3) // Error
To achieve this, I created a type for the func
as follows:
type FuncType = (param: keyof typeof variable) => any
const func: FuncType = ...
However, there is a problem. I can only enforce one of the following:
- Ensuring correct typing for the values of
variable
or
- Enforcing the correct typing for the
param
infunc
to accept only keys fromvariable
I'm unable to tackle both of these issues simultaneously.
- If I focus on typing the values of
variable
, then theparam
infunc
ends up being of typestring
, which allows passing any string tofunc
call, leading to incorrect behavior - If I prioritize typing for the
param
infunc
, it restricts to only valid keys but then allows anything as the value forvariable
One potential solution could involve predefining a list of keys ([key1, key2, ...]
) in another type. However, managing two identical lists is not ideal. How can I address both concerns without resorting to this approach?
Typescript playground provides further insight into this issue, along with explanatory comments.