Home > OS >  How to get types for values from objects in an array when the objects don't all have the same k
How to get types for values from objects in an array when the objects don't all have the same k

Time:03-24

Say I have the following array:

const a = [
  {
    id: 1,
    title: 'Z'
  },
  {
    id: 2,
  },
  {
    id: 3,
    title: 'Y'
  },
] as const

I'm trying to derive a type that is the union type of the title keys if they exist, e.g. 'Z' | 'Y'. I am at a loss as to how to accomplish this though.

I've tried extracting the types using bracket notation, but because the keys aren't on every object, the type is any.

// The type here is `any`
type Titles = typeof a[number]['title']

I've tried handling this with conditional types as well, but I'm really out of my depth there and can't get it to work.

CodePudding user response:

You were almost correct, but property 'title' does not exist on every member of type typeof a[number].

You can filter union members with Extract utility type.

type AElem = typeof a[number];
type AElemWithTitle = Extract<AElemWithTitle, {title: string}>;
type ATitles = AElemWithTitle['title']

Playground link

  • Related