3 ms·
The missing feature I want most is type narrowing across chained functions like: arr.filter(a => a.kind === „bar“).map(a => /* a should now be of type Bar just
by quonn 4y ago
The missing feature I want most is type narrowing across chained functions like:
arr.filter(a => a.kind === „bar“).map(a => /* a should now be of type Bar just like in a branch */)
- subarctic 4y agoWait, are you saying they added that in this release? That's awesome!
- dhritzkiv 4y agoThis is not part of this release.
- acdibble 4y agoThis is possible with type predicates, example: https://www.typescriptlang.org/play?#code/C4TwDgpgBAYg9nKBeKBvKA7AhgWwgLigHIAzBIgbigDcsAbAVwMwZwCMIAnKAXwoFgAUKEhQAQlm4p02PISJtJlGvSaEAzsE4BLDAHNeAwUIDGcDJqjb18RCgAUtRs1tQAPuMkBKQk6ZX1WARkAD4VZwA6WWgkWOIyOEohIQATCBM6SWgzC2AoSU4sEEJ7Vw8JTi8AbQBdI1NzSxJtOmAuCBTkfM5CkAjm1q57a1svIwB6cahpqAA9AH4hIA https://www.typescriptlang.org/play?#code/C4TwDgpgBAYg9nKBeK... docs: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates https://www.typescriptlang.org/docs/handbook/2/narrowing.htm...
- silasdavis 4y agoIt was would be nice for this to be automatic but filter does work like this it you pass a type guard as the predicate: ``` arr.filter((a: A): a is A & { kind: 'bar'} => a.kind === 'bar') ``` If you define: ``` function isKind<K extends A['kind']>(kind: K): (a: A) => a is A & { kind: K } { return (a): a is A & { kind: K } => a.kind === kind; } ``` Then you can write: ``` arr.filter(isKind('bar')) ``` and get a properly narrowed return type array
- quonn 4y agoNice, thank you