0

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.

2
  • 3
    This question is kinda related. Hopefully you can take my answer and make it work for your needs. Commented Mar 23, 2022 at 18:39
  • Thanks @kellys! That got me mostly there. It's bewildering why something so seemingly simple should take so much type gymnastics. Commented Mar 23, 2022 at 18:47

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Very nice! Extract is always one of those types I forget existed. @ray-gesualdo should accept this as the answer.
Thanks @Lesiak! That was exactly what I was looking for! For posterity, here's my final solution with a single type used to pull the values: Playground link

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.