Strange error message when accessing undefined property of an enum
🔎 Search Terms
enum, property, does not exist
🕗 Version & Regression Information
Tested 5.8.2
⏯ Playground Link
https://www.typescriptlang.org/play/?#code/KYOwrgtgBAymCWAXAzlA3gKClAEgUQEEAlAFRigF4oBGDAXwwGMB7EZZgG2ADoPmBzABRwkybjAAKBACJ4YASgDcQA
💻 Code
enum Suits {
HEARTS = 1
}
console.log(Suits.SPADES);
🙁 Actual behavior
Property 'SPADES' does not exist on type 'typeof Suits'.
🙂 Expected behavior
- Property 'SPADES' does not exist on type 'Suits'
- Property 'SPADES' does not exist on enum 'Suits'
Additional information about the issue
No response
This is working as intended. typeof Suits refers to the "container object" that contains all the enum values. The error message will refer to Suits when dealing with a value of your enum, e.g.: function foo(v: Suits) { v.missing }
It's essentially the same as:
class Foo {}
Foo.bar
Property 'SPADES' does not exist on type 'Suits'
This would be the error you'd see if you wrote
function fn(x: Suits) {
console.log(x.SPADES);
}
Ah, why do I never get email notifications when @MartinJohns writes a reply.
Also, I'm confused, I thought enums were not a native JavaScript type... wouldn't it just be a number/string/whatever the underlying type is?
Yeah, no, this is definitely bad error reporting when compared to types, which should be more or less the same:
enum Suits {
HEARTS = 1,
CLUBS = "clubs"
}
function func(s: Suits): void {
console.log(s.substring(1));
}
Property 'substring' does not exist on type 'Suits'.
type Suits = 1 | "clubs";
function func(s: Suits): void {
console.log(s.substring(1));
}
Property 'substring' does not exist on type 'Suits'.
Property 'substring' does not exist on type '1'.
Also, I'm confused, I thought enums were not a native JavaScript type... wouldn't it just be a number/string/whatever the underlying type is?
Typescript does not operate on underlying native types, it operates on the types as defined in typescript.
Regarding the OP... in Suits.SPADES, Suits does not refer to the type Suits, it refers to the value Suits. The type of the value Suits is typeof Suits. There is no named type to reference, just like when we refer to the type of a unique symbol, where its type is typeof MySymbol.
For another analogy, consider class X { }. This defines an instance type X, and it defines a value X, which is a constructor and whose type is typeof X.
This issue has been marked as "Not a Defect" and has seen no recent activity. It has been automatically closed for house-keeping purposes.