[英]How can I get the type of a keyof variable in Typescript?
I have the following interface:我有以下界面:
interface MyInterface {
a: string
b: number
}
and the following Function:以及以下 Function:
function myFunction(key: keyof MyInterface, someItem: MyInterface) {
if (key === "a") {
throw new Error("Key is not corresponding to a number")
}
return someItem[key]
}
It's working, but I have a much bigger interface and I'd like to avoid hardcoding all the keys, that don't correspond to a number.它正在工作,但我有一个更大的界面,我想避免对所有与数字不对应的键进行硬编码。 Is there an easy way to do this?
是否有捷径可寻?
We can get all the number keys with a type like this:我们可以得到所有类型如下的数字键:
type NumberKeys<T> = {
[K in keyof T]: T[K] extends number ? K : never;
}[keyof T];
Mapping over each key, we test if each key's value is a number.映射到每个键,我们测试每个键的值是否为数字。 If it is, we map it to itself, otherwise, it's
never
.如果是,我们将 map 返回给它自己,否则,它
never
。
Then finally, we get all of the results as a union with [keyof T]
.最后,我们将所有结果作为与
[keyof T]
的联合得到。 Because T | never
T | never
T | never
is always T
, we only get the keys that are numbers left. T | never
总是T
,我们只得到剩下数字的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.