我正在使用帶有 React 的 Typescript 并努力獲得正確的型別。我想要實作的是,對于介面 Car,如果carColor為“藍色” ,則屬性colorId是必需的,否則不應包含它。關于如何實作這一目標的任何反饋?
interface Car {
carBrand: string;
carColor: 'black' | 'blue';
colorId?: string;
}
uj5u.com熱心網友回復:
您可以使用泛型和Omit.
創建一個BaseCar具有carBrand,carColor和carId屬性的介面,然后創建一個Car有條件地決定colorId屬性的型別。
interface BaseCar {
carBrand: string;
carColor: "black" | "blue";
colorId: string;
}
type Car<T extends "black" | "blue"> = 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"
};
uj5u.com熱心網友回復:
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"
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/494429.html
標籤:javascript 反应 打字稿
