Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何过滤typescript中的对象数组,以便只剩下包含可选键的对象(并且typescript知道)?_Javascript_Typescript - Fatal编程技术网

Javascript 如何过滤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

这与带有严格空检查的typescript有关。假设您有一个接口,例如:

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
是必需的。语法有点冗长,但它可以工作