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

Typescript: Define if property should be included based on value of other property

I’m using Typescript with React and struggling to get a type correct.. What I am trying to achieve is that for the interface Car the property colorId is required if carColor is ‘blue’ otherwise it should not be included. Any feedback on how to achieve this?

interface Car {
    carBrand: string;
    carColor: 'black' | 'blue';
    colorId?: string;
}

>Solution :

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

type CarColors = "black" | "blue";

// create generic that passed color as asgument
interface Car<C extends CarColors = "black"> {
  carBrand: string;
  carColor: C;
  colorId?: string;
}

// create conditional type that omits carColor when color is black
type ColoredCar<C extends CarColors = "black"> = C extends "blue" ? Car<"blue"> : Omit<Car, "carColor">;

// use agrument blue to require color
const myCar: ColoredCar<"blue"> = {
  carBrand: "bmw",
  carColor: "blue",
  colorId: "123"
};

// otherwise it is omitted 
const myCar2: ColoredCar = {
  carBrand: "bmw",
  colorId: "123"
};
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

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading