microsoft / microsoft/TypeScript
instanceof narrowing should use InstanceType
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.4k
- Merge medio
- 1g 19h
- PR unite (30g)
- 117
Descrizione
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.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia riproducendo l’esempio TypeScript alla base del problema e verificando come si comporta attualmente il restringimento generico con instanceof. Segui il restringimento del flusso di controllo del compilatore e la gestione di InstanceType per determinare dove verrebbe modellata la relazione proposta, quindi aggiungi test mirati che mostrino il restringimento previsto e confermino che il comportamento esistente venga preservato.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- typescript
- Ambito
- compilers
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100