instanceof narrowing should use InstanceType #55241
Labels
Awaiting More Feedback
This means we'd like to hear from more people who would be helped by this feature
Suggestion
An idea for TypeScript
Suggestion
π Search Terms
instanceof, narrow, generic, typeof
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
value instanceof SomeClass
narrowsvalue
to SomeClass in subsequent flow. However,value instanceof someClass
, wheresomeClass
is defined assomeClass: T
andT extends typeof BaseClass
, only narrowsvalue
toBaseClass
rather thanInstanceType<T>
.See also #28936, though in this case I'm not referencing
constructor
at all.π Motivating Example
If you want to downcast in a class hierarchy, you use
instanceof
. JavaScript's dynamism even allows you to dynamically pick the class to cast to. However, TypeScript doesn't understand that when the class is specified using generics, which prevents you from returning a corresponding instance type.π» Use Cases
We are using this for a more realistic version of the example, parsing a serialized format into a type hierarchy. Some callers know that the serialized data should be a specific subclass, and that there should be an error if it doesn't match that subclass, and so it's convenient if the class you call
parse
on decides the type you get back.Workarounds:
parse
always return Base, downcast at call sites. Verbose:if (!(result instanceof Sub1)) throw new Error("β¦")
.instanceof
. This works but is unchecked by the compiler, and of course adds a small bit of overhead because the function won't be compiled away.as InstanceType<T>
to tell TypeScript we know what we're doing. Also works, also unchecked, but probably the workaround I'd recommend for now.The text was updated successfully, but these errors were encountered: