Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wangkailang opened this issue Jul 29, 2022 · 0 comments
Open

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

wangkailang opened this issue Jul 29, 2022 · 0 comments
Labels
documentation Improvements or additions to documentation

Comments

@wangkailang
Copy link
Owner

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[];
@wangkailang wangkailang added the documentation Improvements or additions to documentation label Jul 29, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant