Home > Back-end >  How to type a computed property name?
How to type a computed property name?

Time:01-14

const foobar = <T extends 'a' | 'b' | 'c'>(name: T) => ({
  [name]: name,
  [`${name}Copy`]: name
})

const result = foobar('a') // typeof result is { [x: string]: "a" }

How to type a computed property name here?

I want foobar('a') to return { a: "a", aCopy: "a" } instead of { [x: string]: "a" }.

CodePudding user response:

You can explicitly tell typescript about the return type

const foobar = <T extends 'a' | 'b' | 'c'>(name: T) => ({ [name]: name }) as Record<T, T>
  •  Tags:  
  • Related