reactjs - 在检查对象上是否存在该属性后仍出现“属性在类型 'object' 上不存在”错误
问题:我正在尝试创建一个类型保护,它应该检查某些值是否存在于类型为 unknown 的属性上。
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;
};
上面的例子很简化,但完全代表了我的问题。TypeScript 似乎无法理解,如果 "count" in test 为 true,那么 test 上应该可以访问 count。我遗漏了什么吗?
答案#1
你可以试试这个:
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
如果代码检查工具告诉你不要使用 any,我建议对这个特定的函数禁用它们,因为你已经在检查属性的存在性和类型。
编辑:这里有一个更详细的示例,说明你如何使用 unknown 以及为什么它不能像 any 一样使用。
