-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Closed
Labels
Out of ScopeThis idea sits outside of the TypeScript language design constraintsThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScriptAn idea for TypeScript
Description
In general I thought that using enums is "compatible" with using literal types - (where enums give better support for refactoring, Find all references, intellisense etc.), but seems it's not the case:
Consider the code:
enum S {
A, B, C
}
type T = 0 | 1 | 2
function aTest(a: S) {}
function aTest2(a: S.A | S.B) {}
function bTest(b: T) {}
function bTest2(b: 0|1) {}
aTest(5) // BAD: Does not throw an error
aTest2(S.C) // GOOD: Throws an error
aTest2(5) // BAD: Does not throw an error
bTest(5) // GOOD: Throws an error
bTest2(5) // GOOD: Throws an error
const a:S = 5 // BAD: Does not throw an error
const b:T = 5 // GOOD: Throws an errorSomewhere deep in the search one can find this explanation (not in the docs) #8020 (comment) that TS does not distinguish between flag and non-flag enums - that's why no errors where one would expect
Maybe it would be worth introducing it ? - because I guess a lot of people would prefer enums to be used as unions and have TS throw an error if someone tries to assign wrong values.
It will be even more inconsistent if string enums will make it to TS: #1206 (comment)
The same example then:
enum S: string {
A,
B = "X",
C
}
type T = 'A' | 'X' | 'C'
function aTest(a: S) {}
function aTest2(a: S.A | S.B) {}
function bTest(b: T) {}
function bTest2(b: 0|1) {}
aTest('W') // GOOD: Error
aTest2(S.C) // GOOD: Error
aTest2('W') // GOOD: Error
bTest(5) // GOOD: Error
bTest2(5) // GOOD: Error
const a:S = "W" // GOOD: Error
const b:T = "W" // GOOD: Errorigolopolosov
Metadata
Metadata
Assignees
Labels
Out of ScopeThis idea sits outside of the TypeScript language design constraintsThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScriptAn idea for TypeScript