Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

conditionally check a string in typescript generics

Given the following generic

type WheneverPossible<T extends "boy" | "girl"> =  ...

I want to check conditionally on this generic like the following:

type WheneverPossible<T extends "boy" | "girl"> =  T === "boy" ? { numOfBalls: number } : { numOfDolls: number }

Is there a possibility to do something like this in Typescript?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is possible just use the extends keyword

type WheneverPossible<T extends "boy" | "girl"> =  T extends "boy"
  ? { numOfBalls: number }
  : { numOfDolls: number }

playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use