gpt4 book ai didi

javascript - 如何过滤 typescript 中的对象数组,以便只留下包含可选键的对象(并且 typescript 知道)?

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:22 25 4
gpt4 key购买 nike

这与具有严格空检查的 typescript 有关。假设您有一个界面,例如:

interface Name {
firstName?: string;
lastName?: string;
}

你有一个 Name[] 数组。

我如何过滤这个数组,让 typescript 知道 firstName 存在?例如:

names.filter(name => !!name.firstName).map(name => {
// inside here, typescript still thinks name.firstName is possibly undefined
// but it should be aware that we have already filtered out elements with an
// undefined firstName
})

最佳答案

filter 接受一个可以作为类型保护的函数。 Typescript 不会为函数推断类型保护,但您可以将返回类型显式定义为类型保护:


interface Name {
firstName?: string;
lastName?: string;
}
declare const names: Name[];
names
.filter((name): name is Name & { firstName: string } => !!name.firstName)
.map(name => {
name.firstName.big()
});


Play

上面我们定义了 name 参数将是 Name 但我们使用交集添加了 firstName 是必需的。语法有点冗长,但它有效。

关于javascript - 如何过滤 typescript 中的对象数组,以便只留下包含可选键的对象(并且 typescript 知道)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57539450/

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