如何过滤打字稿中的对象数组,以便仅留下包含可选键的对象(并且打字稿知道)?

Lee*_*idt 3 javascript typescript

这适用于具有严格空检查的打字稿。假设您有一个接口,例如:

interface Name {
  firstName?: string;
  lastName?: string;
}
Run Code Online (Sandbox Code Playgroud)

你有一个Name[]数组。

我怎样才能以打字稿知道存在的方式过滤这个数组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
})
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 5

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()
    });


Run Code Online (Sandbox Code Playgroud)

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