Javascript 如何过滤typescript中的对象数组,以便只剩下包含可选键的对象(并且typescript知道)?
这与带有严格空检查的typescript有关。假设您有一个接口,例如:Javascript 如何过滤typescript中的对象数组,以便只剩下包含可选键的对象(并且typescript知道)?,javascript,typescript,Javascript,Typescript,这与带有严格空检查的typescript有关。假设您有一个接口,例如: interface Name { firstName?: string; lastName?: string; } 您有一个名称[]数组 我如何过滤这个数组,使typescript知道firstName存在?例: names.filter(name => !!name.firstName).map(name => { // inside here, typescript still thinks n
interface Name {
firstName?: string;
lastName?: string;
}
您有一个名称[]
数组
我如何过滤这个数组,使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()
});
上面我们定义了name
参数将是name
,但是使用交集我们添加了firstName
是必需的。语法有点冗长,但它可以工作