-
Notifications
You must be signed in to change notification settings - Fork 12.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Using string enum as key in {[key]: Type} throws not an index signature #22892
Comments
the oposite is true as well, since the type of For these two issues the type assertion consider defining the function as function map(dict: object, transform: (key: string, value: string) => void) { ... } or function map<K extends string>(dict: Record<K, string>, transform: (key: string, value: string) => void) { ... } |
That's presuming I control the definition of I feel like I ought to be able to pass a string enum into a function that requires a Is the solution when I don't control map to do |
it is unsafe, since the index signature on the enum is really |
Thanks. The index signature on |
Another case with standard enums: enum MyEnum {
ValA = 0,
ValB = 1,
}
type IEnumTpProp<R> = {[key in keyof typeof MyEnum]: R };
var X: IEnumTpProp<string> = {
ValA: "text1",
ValB: "text2",
0: "error" // expected: error; current: error; //OK
};
X[MyEnum.ValA] = "no error??"; // current: no error; expected: error // KO
X[MyEnum[MyEnum.ValA]] = "no error"; // current: no error; expected: no error // OK |
@dardino i am afraid this is a different issue. all objects can be indexed with strings/numbers and result in an |
This would be super problematic because we always allow expressions of the form |
This can now be easily done with the new template literal types introduced in 4.1: enum X {
A = 'a',
B = 'b',
}
type ValueOfX = `${X}`
type Y = {
[P in ValueOfX]?: number;
}
let cc: Y = {
a: 0,
c: 1, // error: c does not exist in type Y
} |
TypeScript Version: 2.9.0-dev.20180325
Search Terms: string enum index signature cast
Code
Expected behavior:
Both
map
calls succeed, because a string enum is essentially a{[key: string]: string}
. I ought to be able to use it anywhere that needs something indexed by string (as long as the values are appropriate).Actual behavior:
index.ts(14,5): error TS2345: Argument of type 'typeof Fruits' is not assignable to parameter of type 'StringDict'.
Index signature is missing in type 'typeof Fruits'.
index.ts(19,5): error TS2352: Type 'typeof Fruits' cannot be converted to type 'StringDict'.
Index signature is missing in type 'typeof Fruits'.
Playground Link
Related Issues:
#20011, #18029, #16760
The text was updated successfully, but these errors were encountered: