gpt4 book ai didi

typescript - 使用 `find` 缩小数组中的元素

转载 作者:行者123 更新时间:2023-12-05 02:08:29 26 4
gpt4 key购买 nike

如果我有一个由联合类型的项目填充的数组,我想在数组中找到一个元素并使用它,从我的 find 知道我已经缩小了类型,如何我做到了吗?

也就是说,如果我有以下类型:

interface A {
text: string;
}
interface B {
type: string;
}
type C = A|B;

和下面的代码

const arr: Array<C> = [....]

我想找到 arr 的第一个具有 type 属性的元素。

从逻辑上讲,我认为这是由

const output = arr.find(child => {
if ('type' in child) return true;
return false
})

这似乎应该将 output 的类型缩小为 B,但事实并非如此。编译器似乎仍然认为 outputC 类型。

最佳答案

在您的案例中实现类型保护的类型安全方法是

function isB(c: C): c is B {
if ('type' in c) {
return typeof c.type === 'string';
}

return false;
}

另一个答案没有考虑这样一个事实,即有有效的 C 值具有不是字符串的 type 属性。

关于typescript - 使用 `find` 缩小数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60842548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com