microsoft / microsoft/TypeScript
instanceof narrowing should use InstanceType
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.3k
- Ø Merge
- 1 T. 19 Std.
- Gemergte PRs (30 T.)
- 117
Beschreibung
Suggestion
🔍 Search Terms
instanceof, narrow, generic, typeof
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code. (Stronger narrowing logic can result in additional errors being emitted.)
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
value instanceof SomeClass narrows value to SomeClass in subsequent flow. However, value instanceof someClass, where someClass is defined as someClass: T and T extends typeof BaseClass, only narrows value to BaseClass rather than InstanceType<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.
class Base {
private readonly field: number;
constructor(field: number) {
this.field = field;
}
private downcastTo<T extends typeof Base>(subclass: T): InstanceType<T> {
if (this instanceof subclass)
return this; // error: Type 'this' is not assignable to type 'InstanceType<T>'
throw new TypeError(`expected ${subclass.name}, got ${this.constructor.name}`);
}
static parse<T extends typeof Base>(this: T, input: string): InstanceType<T> {
let result: Base;
if (input == "Sub1") {
result = new Sub1(1);
} else if (input == "Sub2") {
result = new Sub2(2);
} else {
throw new TypeError("invalid input");
}
return result.downcastTo(this);
}
}
class Sub1 extends Base {
// ...
}
class Sub2 extends Base {
// ...
}
// Normal static method usage
const base: Base = Base.parse("sub1")
// Now also valid, with stronger checks
const sub1: Sub1 = Sub1.parse("sub1");
💻 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:
- Have
parsealways return Base, downcast at call sites. Verbose:if (!(result instanceof Sub1)) throw new Error("…"). - Use a type-predicate wrapper function for
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. - Use
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, das zugrunde liegende TypeScript-Beispiel zu reproduzieren und zu prüfen, wie sich die Verengung von Generics mit instanceof derzeit verhält. Verfolge die Kontrollflussverengung des Compilers und die Behandlung von InstanceType, um zu bestimmen, an welcher Stelle die vorgeschlagene Beziehung modelliert würde, und füge anschließend fokussierte Tests hinzu, die die erwartete Verengung zeigen und bestätigen, dass das bestehende Verhalten erhalten bleibt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Feature
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100