Issue
I have an enum and I want to add its values to an interface, but getting this error:
A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.(1169)
How could I use enum values as interface properties without having to create a second enum with the reverse key/values?
enum Fields {
'name' = 'field1',
'age' = 'field2',
'custom field' = 'field3',
}
interface Person {
id: string;
[Fields['custom field']]?: string;
}
Solution
I think you can achieve what you want with an intermediate type, as follows:
enum Fields {
'name' = 'field1',
'age' = 'field2',
'custom field' = 'field3',
}
type FieldsObject = {
[K in Fields]? : string
}
interface Person extends FieldsObject {
id: string;
}
const p: Person = {
id: "abc",
field1: "",
field3: "",
}
TypeScript Playground showing this
Answered By - user2740650
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.