Home > Mobile >  typescript: Use enum value as key in interface containing spaces
typescript: Use enum value as key in interface containing spaces

Time:12-05

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

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;
}

CodePudding user response:

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

CodePudding user response:

I have a solution, but it's ugly: basically, use a mapped type to define that property, and then intersect with a regular object type to define the rest of the properties. I used Simplify to make the result more readable.

type Simplify<T> = T extends unknown ? {[K in keyof T]: T[K]} : never

type Person = Simplify<{
  id: string;
} & {
  [K in typeof Fields['custom field']]?: string
}>

Hovering over Person in the Typescript Playground shows the result is equivalent to:

type Person = {
    id: string;
    field3?: string | undefined;
}

Playground Link

  • Related