Home > database >  How to get the second property type from an array of objects?
How to get the second property type from an array of objects?

Time:01-16

I have an object mapping other objects containing id and name.

I need to get the name type from its id.

My attempt was:

const obj = {
    foo: { id: 1, name: 'one' },
    bar: { id: 2, name: 'two', },
    baz: { id: 3, name: 'three' },
} as const

type Obj = typeof obj;
type ValueOf<T> = T[keyof T];
type Ids = ValueOf<Obj>['id'];

type GetName<T extends Ids> = (ValueOf<Obj> & { id: T })['name']

type Foo = GetName<1>

But Foo is "one" | "two" | "three", while I expected to be "one".

How to solve it?

CodePudding user response:

By Extract-ing the members instead of intersecting them with { id: T }:

type GetName<T extends Ids> = Extract<ValueOf<Obj>, { id: T }>['name']

Playground

  • Related