-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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<T>.filter should be able to refine T|undefined to T #20707
Comments
This is already possible, you just need to define an explicit user-defined type guard: function notUndefined<T>(x: T | undefined): x is T {
return x !== undefined;
}
if (ids) {
relevantEntities = ids.map(id => entities.get(id)).filter(notUndefined);
} |
That only works if you pass the type guard as a function reference and don't, for example, call it with an arrow function. This does not work: function notUndefined<T>(x: T | undefined): x is T {
return x !== undefined;
}
if (ids) {
relevantEntities = ids.map(id => entities.get(id)).filter(entity => notUndefined(entity));
} As far as I know, if you need or want to use an arrow function you need to tell the compiler that you know better than it with an assertion: function notUndefined<T>(x: T | undefined): x is T {
return x !== undefined;
}
if (ids) {
relevantEntities = ids.map(id => entities.get(id)).filter(entity => notUndefined(entity)) as EntityType[];
} |
Thanks @RyanCavanaugh - that solution does appear to work as-is. It is, however, fairly unintuitive (hence my being here in the first place!) and I think it would be immensely helpful if this "just worked" out of the box. I think it's a fairly common pattern, particularly when working with a normalized store of entities (e.g. Redux). At the very least, having this documented on the Typescript website (rather than digging around in github issues and stackoverflow) would go a long way for the language's usability, even if it's not (currently?) practical to add first-class support into the language. |
Duplicate of #20812 |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
TypeScript Version: 2.6.1
Code
Note that I have tried many variants of the argument to
filter
(x => !!x
,x => x !== undefined
, etc). I'm only usingBoolean
here since it works in FlowFurther note that making the following change allows the error checker to proceed, but only through basically lying about the data:
Expected behavior:
Assignment proceeds without error, since any
undefined
values produced in themap
operation are filtered out.Actual behavior:
The text was updated successfully, but these errors were encountered: