Home > database >  Typescript creating Object Type from Readonly Array
Typescript creating Object Type from Readonly Array

Time:04-20

I have an array like so:

const arr = [{id: 2, name: "hotdog"}, {id: 3, name: "chicken"}] as const

And I want to generate a type from it, that looks like this:

type ArrTransform = { readonly hotdog: 2, readonly chicken: 3 }

I've tried to do something like this (and many other attempts, but this was the closest I could get):

type ArrToObject<T extends ReadonlyArray<{name: string, id: number}>> = {
  [key in T[number]["name"]]: T[number]["id"]
}

But it doesn't map names with the exact id, it generates a union from all the ids (2 | 3) - which is not what I want.

Is it even possible to create a generic like this in Typescript?

CodePudding user response:

Access each whole individual object with only [number], then separately extract the name property (assert that it'll be the key with as) and the id after the colon.

type Obj = {
    [T in typeof arr[number] as T["name"]]: T["id"]
}
  • Related