Typescript:定义if属性应该基于其他属性的值来包含



我正在使用React的Typescript并努力获得正确的类型。我想要实现的是,对于接口Car属性colorIdcarColor"蓝">否则它不应该被包括在内。对如何实现这一点有什么反馈吗?

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

可以使用泛型和Omit

创建具有carBrand,carColorcarId属性的BaseCar接口,然后创建有条件地决定colorId属性的Car类型。

interface BaseCar {
carBrand: string;
carColor: "black" | "blue";
colorId: string;
}
type Car<T> = T extends "black" ? Omit<BaseCar, "colorId"> : BaseCar;
const blueCar: Car<"blue"> = {
carBrand: "tesla",
carColor: "blue",
colorId: "123",
};
const blackCar: Car<"black"> = {
carBrand: "honda",
carColor: "black",
};
// @ts-expect-error
const blueCarWithoutId: Car<"blue"> = {
carBrand: "tesla",
carColor: "blue",
};
const blackCarWithId: Car<"black"> = {
carBrand: "honda",
carColor: "black",
// @ts-expect-error
colorId: "123",
};
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"
};

最新更新