3 ms·
You can use a type guard[1] as an argument to Array.filter, but the function has to be explicitly typed as such. I don't know why the type isn't narrowed in A
by abrioy 5y ago
You can use a type guard[1] as an argument to Array.filter, but the function has to be explicitly typed as such.
I don't know why the type isn't narrowed in Array.filter like it is in if statements without this weird workaround.
const array: (number | string)[] = [];
const mixedArray = array.filter(value => typeof value === 'string');
// mixedArray: (number | string)[]
const arrayOfString = array.filter((value): value is string => typeof value === 'string');
// arrayOfString: string[]
This example in Typescript playground: https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgJwXAngLhgCjAVwLYBGApgjAD4zQICWYA5gJQDaAujALwysDcAUL6Eiw81AB5EAJgEEkqDvFkoAdADNqAGyglMANzjqcRDgD4YUFAAciIFTD0Gj7JzADkVWnRcM+Aeh8wRcWlFDGx8YlIKd3pmFgFwaAVkFAB5FQBlKBp6eURk1Q0tBExdfUMGDHtDGGoISiyPEzNLa1sqx2c3BvovX3881DTM7LoMaLpWIA https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgJwXA...
[1]: https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types https://www.typescriptlang.org/docs/handbook/advanced-types....
- amitport 5y agoOh so there is an overload! filter<U extends T>(pred: (a: T) => a is U): U[]; Additionally, getting TS better at inferring type guards is an open issue (literally): https://github.com/microsoft/TypeScript/issues/38390 https://github.com/microsoft/TypeScript/issues/38390