microsoft / microsoft/TypeScript
Control flow not formed when using consts
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.3k
- Ø Merge
- 2 T. 4 Std.
- Gemergte PRs (30 T.)
- 132
Beschreibung
TypeScript Version: 2.0.3
Code
interface Releasable {
release(): void;
}
const typeOfNumber: string = 'number';
function release(releasable: number | Releasable): void {
if(typeof releasable === typeOfNumber) {
allocated.splice(allocated.indexOf(releasable), 1);
} else {
releasable.release();
}
}
Expected behavior:
interface Releasable {
release(): void;
}
const typeOfNumber: string = 'number';
function release(releasable: number | Releasable): void {
if(typeof releasable === typeOfNumber) {
allocated.splice(allocated.indexOf(releasable), 1); // Ok, typeof releasable is number here
} else {
releasable.release(); // Ok, typeof releasable implements Releasable here
}
}
Actual behavior:
interface Releasable {
release(): void;
}
const typeOfNumber: string = 'number';
function release(releasable: number | Releasable): void {
if(typeof releasable === typeOfNumber) {
allocated.splice(allocated.indexOf(releasable), 1); // [ts] Argument of type 'number | Releasable' is not assignable to parameter of type 'number'. Type 'Releasable' is not assignable to type 'number'.
} else {
releasable.release(); // [ts] Property 'release' does not exist on type 'number | Releasable'.
}
}
Currently type guards are only limited to literals. Type guards are consumed at compile time and from this taken in mind variables defined with let or var seems natural to not result in proper control flow but type guards using constants defined with const should result in a proper type guard. Since the compiler already knows that consts will not change their value ans so their value should be checked dose it evaluate to known typeof return value to form a proper control flow else to result in a [ts] error ...
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 bereitgestellte TypeScript 2.0.3-Beispiel auszuführen, und vergleiche die gemeldeten Fehler mit dem erwarteten Narrowing-Verhalten. Verfolge anschließend die Behandlung von Kontrollfluss-Typ-Guards des Compilers für typeof-Vergleiche und füge Tests hinzu, die zeigen, dass ein unveränderter const-String Narrowing ermöglicht, während veränderliche Variablen dies nicht tun.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Feature
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Klar beschrieben
- Anfängerfreundlichkeit
- 35/100