Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

typescript: Use enum value as key in interface containing spaces

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)

https://www.typescriptlang.org/play?ts=4.5.2#code/KYOwrgtgBAYglsANgEwM5QN4CgpQOQgCGEweUAvPgGYIoCMeANDvoQOakW541LIBMTFngDGYVABcA9tF4oylHrWQBmIQF8sWOCAnAATlUIjgUAAoHUUkJhZxkALiiT9OtgG4WAbXh9UX0XFpWWU8AF0wgH4nFzdPdSA

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading