How does TypeScript's structural type checking treat two DIFFERENT numeric enums that happen to have the same underlying values?
Short answer
Unlike most structural comparisons, TypeScript treats numeric enum members as NOMINALLY distinct from each other by name even when their underlying values match — you cannot assign a member of one numeric enum to a variable typed as a different numeric enum, even if both equal…
Advertisement
AModel answer
Unlike most structural comparisons, TypeScript treats numeric enum members as NOMINALLY distinct from each other by name even when their underlying values match — you cannot assign a member of one numeric enum to a variable typed as a different numeric enum, even if both equal 0, though plain numbers CAN still be assigned to a numeric enum variable.
enum A { X = 0 }
enum B { Y = 0 }
let a: A = A.X;
// let bad: A = B.Y; // Error: Type 'B' is not assignable to type 'A'
let ok: A = 0; // OK -- plain numbers are still assignableReal-world example
Understanding a confusing compiler error when trying to pass one enum's member where a structurally-identical-looking different enum is expected.
Likely follow-ups
- Does this same nominal-like distinctness apply to string enums as well?
Related topics