Skip to content

array filter 泛型返回具体元素类型 #1

Open
@wangkailang

Description

@wangkailang

array filter 泛型返回具体元素类型

is 指定推导结果类型:

6B5s06z32u

filter<S> S 可以忽略不填,但是返回值 value is S 必须手写

type Alice = {
  name: string;
  department: string;
}
type Bob = {
  name: string;
  department: boolean;
}
type Carl = {
  name: string;
  department: number;
}

type AllName = Alice | Bob | Carl;

const employees: AllName[] = [
  { name: 'Alice', department: 'accounting' },
  { name: 'Bob', department: true },
  { name: 'Carl', department: 10 },
];

const isAlice = (obj: AllName): obj is Alice => obj.name === 'Alice';

const result = employees.filter(isAlice);
// result => Alice[];

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions