Dynamically Allocate Function Types with Conditional Types in TypeScript

InstructorRares Matei

Share this video with your friends

Send Tweet

Conditional types take generics one step further and allow you to test for a specific condition, based on which the final type will be determined. We will look at how they work on a basic level and then leverage their power to allocate function types dynamically based on the type of their parameters, all without any overloads.

Dean
~ 5 years ago

I tried to read on conditional types and nothing made sense... but your video really nailed it down in 3 minutes.. good job!!

Anup
~ 5 years ago

Excellent video!!! Can you please help me understand how one would implement getItem() and differentiate between whether id is a number or string?

Ian Jones
~ 5 years ago

Anup, That's a good question. Let me see if I can find an answer.

Rares Mateiinstructor
~ 5 years ago

Hi Anup, very good question!

The example I gave above is very useful to consumers of that API.

When implementing it unfortunately, there's a current a limitation of the TS compiler where it can't safely infer whether you're returning the correct value. More details here:

  • https://github.com/microsoft/TypeScript/issues/22735
  • https://github.com/microsoft/TypeScript/issues/24929

So you will have to use casting:

let itemService: IItemService = {
  getItem: <T extends string | number>(id: T) => {
    const books: Book[] = [
      { id: "1", tableOfContents: [] },
      { id: "2", tableOfContents: [] }
    ];
      const tvs: Tv[] = [
      { id: 1, diagonal: 40 },
      { id: 2, diagonal: 50 }
    ];
    if (typeof id === "string") {
      return <T extends string ? Book : Tv>books.find(book => book.id === id)!;
    } else {
      return <T extends string ? Book : Tv>tvs.find(tv => tv.id === id)!;
    }
  }
};