1

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?

1 Answer 1

3

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"]
}
Sign up to request clarification or add additional context in comments.

2 Comments

It is possible to make a generic version as well: playground link
Damn this is good! What is this sorcery? Also thanks a ton @Bbrk24, your playground link was more or less exactly what my actual use case is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.