I am struggling to create an interface that uses values from an Enum.
enum TestEnum {
'VAL1' = 'TEST1',
'VAL2' = 'TEST2'
}
interface IMyInterface {
[TestEnum[key in TestEnum]]: {
// some code
}
}
const objToType: IMyInterface = {
TEST1: { / ** \ }
TEST2: { / ** \ }
}
It throws an error
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.
What's the problem here?
CodePudding user response:
I think the confusing bit is that [key in TestEnum]
returns the "values" of the enum rather than the "keys" (if you want to iterate the keys you'd use [key in keyof TestEnum]
).
This is easy to do using a type
declaration rather than an interface declaration:
enum TestEnum {
'VAL1' = 'TEST1',
'VAL2' = 'TEST2'
}
type IMyInterface = {
[key in TestEnum]: { /* */ }
}
const objToType: IMyInterface = {
TEST1: { },
TEST2: { }
}