比方说,我有一个这样的界面:
interface field {
code: string
name: string
...
}
然后我想创建一个变量,其值仅接受来自该接口的成员
let key: "code" | "name" ...
如果接口成员较多的话,代码行会很长,有解决办法吗?
有没有一种快速的解决方案可以使用上面的打字稿根据接口的成员验证变量?
---
谢谢你。
这是
keyof
运算符的用例:
interface field {
code: string
name: string
// ...
}
let key: keyof field;
key = "code"; // Okay
key = "other"; // Type '"other"' is not assignable to type 'keyof field'.