代码
const obj = {};
if ('a' in obj) console.log(42);
不是 typescript (没有错误)。我明白为什么会这样。此外,在 TS 2.8.1 中,“in”用作类型保护。
但是,有没有办法检查属性是否存在,但是如果属性没有在obj的接口(interface)中定义则报错?
interface Obj{
a: any;
}
我不是在谈论检查未定义...
最佳答案
您不会收到错误,因为您使用字符串来检查该属性是否存在。
你会得到这样的错误:
interface Obj{
a: any;
}
const obj: Obj = { a: "test" };
if (obj.b) // this is not allowed
if ("b" in obj) // no error because you use string
如果您希望类型检查适用于字符串属性,您可以添加 index signatures using this example
关于javascript - typescript 以类型安全的方式检查对象中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49707327/