'How to get types for values from objects in an array when the objects don't all have the same keys in TypeScript?

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.



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1