Typescript creating Object Type from Readonly Array

Issue

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?

Solution

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"]
}

Answered By – CertainPerformance

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.