microsoft / microsoft/TypeScript
Checking union type where key is enum tricks compiler
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: 3.9.2
Search Terms:
enum refinement
checking interface enum
Code
// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
enum Fish {
blue= 1,
red= 2
}
enum Crab {
purple= 2
}
interface IFish {
type: Fish,
name: string,
}
interface ICrab {
type: Crab,
shell: string
}
const crab = {type: Crab.purple, shell: "hard"}
function determineAnimal(animal: ICrab | IFish) {
if (animal.type === Fish.red) {
console.log("fish")
console.log(animal.name)
} else if (animal.type === Crab.purple) {
console.log("crab")
console.log(animal.shell)
} else {
console.log("fell through")
}
}
determineAnimal(crab)
Expected behavior: The program does not typecheck because checking against the enum does not prove the animal is an IFish
Actual behavior: The program typechecks and incorrectly determines the type of the crab, logging undefined.
Playground Link: link
Related Issues:
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
Reproduziere das in sich geschlossene enum- und union-Beispiel mit dem tsc-Befehlszeileneinstiegspunkt und bestätige das fehlerhafte Narrowing-Verhalten. Verfolge, wie der Compiler enum-Vergleiche mit union-Mitgliedern prüft, und füge Tests hinzu, die zeigen, dass der Crab-Fall nicht auf IFish-Eigenschaften zugreifen kann und dass das gemeldete erwartete Verhalten durchgesetzt wird.
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
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100