TypeScript Version: 2.1.1 / nightly (2.2.0-dev.201xxxxx)
Code
public enum MyEnum
{
A=1,
B=2,
C=3
}
public type MyEnumKeys=keyof MyEnum;
Expected behavior:
MyEnumKeys would contain "A" | "B" | "C"
Actual behavior:
MyEnumKeys contains "toString" | "toFixed" | "toExponential" | "toPrecision" | "valueOf" | "toLocaleString"
This is working as intended. You need to use keyof typeof MyEnum to get 'A' | 'B' | 'C'.
@ahejlsberg How do you suggest getting the values back? Today, this doesn't seem to work:
enum A {
One = "one",
Two = "two"
}
type Key = keyof typeof A // "One" | "Two"
type Val = (typeof A)[Key]
let a: Val = "one" // Error: Type '"one"' is not assignable to type 'A'.
I am happy to file a separate issue for this.
the enum type is a tagged version of the string literal type. so the error you are getting is what i would expect.
@mhegazy I can use keyof to get an interface's keys, and T[keyof T] to get its values. I can also use keyof to get an enum's keys, but is there a way to get the values?
(typeof A)[keyof A] is just A which is just A.One | A.Two.
A.One is a subtype of "one", and is assignable to it, but not the other way around. A.One is a spacial "one" a tagged "one" if you may.
@mhegazy Makes sense. Thanks for the explanation.
Most helpful comment
This is working as intended. You need to use
keyof typeof MyEnumto get'A' | 'B' | 'C'.