'Make function param accepts only keys from variable object
I have an object with defined type:
type Type = { [key: string]: ... }
const variable: Type = {
key1: ...,
key2: ...,
key3: ...,
}
I have a function, and I want that function only accept 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:
type FuncAcceptParamFromAboveVariableKey = <K extends keyof typeof variable>(param: K) => any
const func: FuncAcceptParamFromAboveVariableKey = ...
But I can't achieve this yet:
- If I set as
const variable: Type = {,Khasstringtype and I can pass anything tofunccall - If I set as
const variable = {, I have achieve this but it makevariableundefined type.
How can I achieve both of them without predefined Type with list of keys ([key1, key2, ...]). I don't want to maintain two list of the samething.
Typescript playground for this problem: link
Solution 1:[1]
You have to use helper function that does nothing just validates type.
const makeType = <T extends Type = Type>(obj: T) => obj
const variable = makeType({
key1: 0,
key2: 0,
key3: 0,
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BorisTB |
