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)
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。语法有点冗长,但它有效。
| 归档时间: |
|
| 查看次数: |
1710 次 |
| 最近记录: |