TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)
Code
const Foo = 'foo';
enum MyEnum {
FooValue = Foo
};
Expected behavior:
The following code compiles
Actual behavior:
Computed values are not permitted in an enum with string valued members.
Explanation
My understanding is that computed values are not permitted in type definitions, because that would require the compiler to actually evaluate code. So in the following example, if I've chosen to define Foo as let or var the compiler would have no way of telling what the value of this variable is at the time of creating the type definition. Similar reasoning would apply to reference types (irrespectively of which keyword was used to declare them). In case of value types defined as const however, a compiler should make an assumption that such value is immutable imho.
The issue here is that const only refers to the run-time behavior. The value of a const isn't necessarily known at compile-time. For example, it might have been imported from another module and not have a known value.
How about a variable whose type is inferred or defined to be a string literal value? Can that work?
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
@mhegazy What, why is this unactionable, what about my suggestion?
@MadaraUchiha there are limitations here because we have to be able to perform single-file transpilation correctly without necessarily having all types correctly resolved (e.g. under compile-on-save with the isolatedModules flag turned on). The original label still applies.
@RyanCavanaugh Still don't see how. And more importantly, why is it different from numbered enums (which do allow enum values to be assigned to variables). If you have the type resolved to 'foo' at compile time, where's the technical limitation?
@MadaraUchiha brings up a valid point. The example from above (except with a number instead of a string) compiles just fine, shouldn't this fail as well?
const Foo = 0;
enum MyEnum {
FooValue = Foo,
}
Most helpful comment
@MadaraUchiha brings up a valid point. The example from above (except with a number instead of a string) compiles just fine, shouldn't this fail as well?