问题:我正在尝试创建一个类型保护,它应该检查未知类型的属性上是否存在某些值。
interface TestProps {
count: number;
}
const getIsTestShown = (test: unknown): test is TestProps => {
if (test && typeof test === "object") {
if ("count" in test) {
if (typeof test.count === "number") { // ERROR: Property 'count' does not exist on type 'object'.ts(2339)
return true;
}
}
}
return false;
};
上面的例子是简化的,但正好代表了我的问题。打字稿似乎不明白,如果 "count" in test
是真的,计数应该可以在测试中访问。我错过了什么?
你可以试试这个:
interface TestProps {
count: number;
}
const getIsTestShown = (test: any): test is TestProps => {
return typeof test?.count === "number" ?? false;
};
console.log(getIsTestShown({})) // false
console.log(getIsTestShown({ count: 1 })) // true
console.log(getIsTestShown({ count: "1" })); // false
console.log(getIsTestShown({ someOtherProp: "1" })); // false
如果 linters 告诉您不要使用any
,我建议您为此特定功能禁用它们,因为您已经在检查属性和类型是否存在。
编辑:这是一个更详细的示例,说明如何使用unknown
以及为什么它不像any
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句