microsoft / microsoft/TypeScript
Type narrowing with assertions containing truthy literals
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: 4.2.0-dev.20201109
Search Terms:
type narrowing truthy
type narrowing assertion
conditional throw
Code
function test(foo?: number) {
if (!foo) throw new Error();
return foo.toFixed();
}
function testWithLiteralTrue(foo?: number) {
if (!foo && true) throw new Error();
return foo.toFixed();
}
function testWithTruthyLiteral(foo?: number) {
if (!foo && "str") throw new Error();
return foo.toFixed(); // Object is possibly 'undefined'.
}
Expected behavior:
In all three functions typescript would know foo is a number after the assertion.
Actual behavior:
In the last example, testWithTruthyLiteral, typescript complains foo may be undefined. This is the same behavior for all known truthy values except for literal true.
Related Issues:
https://github.com/microsoft/TypeScript/issues/29323
It sounds like from https://github.com/microsoft/TypeScript/issues/29323#issuecomment-454548280 that determining truthiness of expressions could lead to circular dependencies between compiler passes, but that literal true has been special cased. This should be able to be extended to truthy literals without the circular dependency concern.
And for context, like others that have brought up similar issues, this stems from wanting a truthy token that can be used for a minification hook without affecting the types or code execution.
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 mit dem verlinkten TypeScript Playground-Beispiel und vergleiche die drei Funktionen mit dem Literal true und anderen truthy-Literalen. Lies den zugehörigen Issue #29323 und die darin verlinkte Diskussion über die Truthiness-Analyse und Abhängigkeiten zwischen Compiler-Pässen. Als abgeschlossen gilt die Aufgabe, wenn truthy-Literale foo nach dem bedingten throw konsistent einengen, mit Abdeckung für die gemeldeten Fälle.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Klar beschrieben
- Anfängerfreundlichkeit
- 45/100