Home > Software design >  Convert and Array<string> type to an object where the keys are the strings of the array
Convert and Array<string> type to an object where the keys are the strings of the array

Time:11-18

I am trying to create a type transformation which converts an array of strings into an object where the keys are the values of the strings.

type ObjectFromKeys<T extends Array<string>> = {
  [K in keyof T]: string
}

declare const o: ObjectFromKeys<['foo']>
o.foo // Property 'foo' does not exist on type '[string]'

Edit it seems this works:

type ObjectFromKeys<T extends Array<string>> = {
  [K in T as any]: string
}

This seems unsafe, is this the right way to do it?

Edit but it does not throw if the value accessed is not in the array

type ObjectFromKeys<T extends Array<string>> = {
  [K in T as any]: string
}

declare const o: ObjectFromKeys<['foo']>
o.bar // This should fail

CodePudding user response:

You're pretty close to the answer all you have to do is convert an Array<string> into a union, which you can do by T[number]. see below:

type ObjectFromKeys<T extends Array<string>> = {
  [K in T[number]]: string
}

Playground link

  • Related