tsc
permits basic interchangeable usage of two different enum declarations so long as both enum names and each enums members are the same. For example, the below assignments are valid, namespaces
are used here, but this is observed to extend to TS module declarations and separate files.
namespace X {
export enum Colour {
Blue,
Green,
}
}
namespace Y {
export enum Colour {
Green,
Blue
}
}
// assign a Colour enum from Y to a variable with a Colour enum type from X
let greenXY: X.Colour = Y.Colour.Green; // OK
// assign a Colour enum from X to a variable with a Colour enum type from Y
let blueYX: Y.Colour = X.Colour.Blue; // OK
// and equality
let greenX = X.Colour.Green;
let isGreen = greenX == Y.Colour.Green; // OK
Now consider the const
enums with the same structure:
namespace X {
export const enum ConstColour {
Green,
Blue
}
}
namespace Y {
export const enum ConstColour {
Green,
Blue
}
}
// assign a const Colour enum from Y to a variable with a const Colour enum type from X
let greenConstXY: X.ConstColour = Y.ConstColour.Green; // Type 'ConstColour.Green' is not assignable to type 'ConstColour'.(2322)
// assign a Colour enum from Y to a variable with a Colour enum type from X
let blueConstYX: Y.ConstColour = X.ConstColour.Blue; // Type 'ConstColour.Blue' is not assignable to type 'ConstColour'.(2322)
// and equality
let constGreenX = X.ConstColour.Green;
let isConstGreen = constGreenX == Y.ConstColour.Green; // This condition will always return 'false' since the types 'X.ConstColour' and 'Y.ConstColour' have no overlap.(2367)
We know that const
enums are inlined at use sites to the desired value and that tsc
views enums as a union type of its members which is how tsc
knows the types of which enums comprise.
And so if tsc
is able to reliably determine the correct basic usage of two regular enums at compile-time. Why would const
enums differ in this case?