检查对象上是否存在属性后,类型“对象”错误中不存在属性

龙鱼

问题:我正在尝试创建一个类型保护,它应该检查未知类型的属性上是否存在某些值。

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是真的,计数应该可以在测试中访问。我错过了什么?

迈克 S。

你可以试试这个:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章