我正在將 react typescript 與 redux 商店一起使用。我有兩種來自有效負載的物件型別。我想識別有效負載物件型別,以便我可以根據型別執行一些操作。
這些是型別
type Car = {
carID: number,
color: string,
model: string,
score: number
}
type Bus = {
busID: number,
model: string,
type: string
}
type Transports = {
[id: number]: Array<Car | Bus>;
}
interface State {
data: Transports
}
在減速器中,我有一個洗掉方法,其中出現錯誤:
Types of parameters 'x' and 'value' are incompatible.
Type 'Car | Bus' is not assignable to type 'Car'.
在 forEach 回圈上
deleteVehicle: (state: State, action: PayloadAction<Car | Bus>) => {
if("carID" in action.payload){
const { id, carID } = action.payload;
let vehicles = { ...state.data };
vehicles[id].forEach((x: Car) => {
if (x.carID === carID) x.score = 0;
});
state.data = { ...vehicles };
}
}
uj5u.com熱心網友回復:
您可以檢查密鑰是否存在,以便 Typescript 推斷出正確的型別。
deleteVehicle: (state: State, action: PayloadAction<Car | Bus>) => {
const { id, carID } = action.payload;
const vehicles = state.data;
return {
...vehicles,
vehicles[id]: vehicles[id].map((vehicule) => {
if ('carId' in vehicule && vehicule.carId === carId) {
// vehicule will be of type Car
vehicule.score = 0;
}
return vehicule;
}
}
uj5u.com熱心網友回復:
它檢查雙方,可用于型別Carbu not Bus,
解決方案 1:創建一個條件(如果型別是總線,它呼叫x.busID而不是x.carID)。
解決方案 2:更改兩種型別以獲取通用 id
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476049.html
