用于验证字符串变量的 Typescript 接口成员

问题描述 投票:0回答:1

比方说,我有一个这样的界面:

interface field {
    code: string
    name: string
    ...
}

然后我想创建一个变量,其值仅接受来自该接口的成员

let key: "code" | "name" ...

如果接口成员较多的话,代码行会很长,有解决办法吗?

有没有一种快速的解决方案可以使用上面的打字稿根据接口的成员验证变量?

---

谢谢你。

typescript types typescript2.0
1个回答
0
投票

这是

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'.

游乐场链接

© www.soinside.com 2019 - 2024. All rights reserved.