Repository navigation
Infer Type Guard Return Values #5101
Description
Activity
- addedSuggestionAn idea for TypeScriptAn idea for TypeScriptIn DiscussionNot yet reached consensusNot yet reached consensus
on Oct 5, 2015 We should add the overload to the library regardless of this suggestion. Gaelan Steele (@Gaelan) feel free to send us PR for updating the library.
- addedHelp WantedYou can do thisYou can do thisDomain: lib.d.tsThe issue relates to the different libraries shipped with TypeScriptThe issue relates to the different libraries shipped with TypeScriptand removedIn DiscussionNot yet reached consensusNot yet reached consensus
on Oct 5, 2015 - added this to the This milestone has been deleted milestone
on Oct 5, 2015 RyanCavanaugh commented
on Oct 5, 2015 MemberMore actionsAccepting PRs for the lib.d.ts overload.
The more complex portion of inferring type guards based on
returnstatements was declined based on complexity. It's fun and easy to write a curried version of this that works today (with the additional overload forfilter):declare class Foo { bar: number } declare var blah: Object[]; function isInstance<T>(ctor: new(...args: any[]) => T): (x: any) => x is T { return <(x: any) => x is T>(x => x instanceof ctor); } blah.filter(isInstance(Foo))[0].bar // Property bar does exist :)
Reacted by emmanueltouzerycan't quite see how changing
libs.d.tsis able to fix this problem, mind sharing idea?This is not a general fix, this is only a fix for array.filter. By changing the declaration you get the contextual type for the the function expression at the call.
The overload for
Array.filtershould be in already. closing.#16069 now tracks inferring the type guard automatically.
- locked and limited conversation to collaborators
on Jul 31, 2018
If a function returns a type guard, either the result of an
instanceofor the return value of another type guard function, it could be inferred as being a type guard itself. However, it is simply inferred as aboolean.This change would allow the following code to work: