microsoft / microsoft/TypeScript
Checking union type where key is enum tricks compiler
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
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:
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the self-contained enum and union example with the tsc command-line entry point and confirm the incorrect narrowing behavior. Trace how the compiler checks enum comparisons against union members, then add coverage showing that the Crab case cannot access IFish properties and that the reported expected behavior is enforced.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100