![](/img/trans.png)
[英]The intersection 'xxx & xxx' was reduced to 'never' because property 'xxx' has conflicting types in some constituents
[英]The intersection '... & ...' was reduced to 'never' because property '...' has conflicting types in some constituents
我有兩個類定義如下:
class FirstClass {
values: FirstValuesType = {} as FirstValuesType;
setValues(values: FirstValuesType): void {
this.values = { ...values };
}
}
class SecondClass {
values: SecondValuesType = {} as SecondValuesType;
setValues(values: SecondValuesType): void {
this.values = { ...values };
}
}
interface CommonValuesType {
id: number;
property1: string;
property2: string;
}
enum FirstReasonEnum {
A, B, C
}
enum SecondReasonEnum {
X, Y, Z
}
interface FirstValuesType extends CommonValuesType {
reason: FirstReasonEnum;
}
interface SecondValuesType extends CommonValuesType {
reason: SecondReasonEnum;
}
然后我定義了一個常量,它可以是以下類之一:
const model: FirstClass | SecondClass;
當我這樣調用setValues
時:
model.setValues(newValues);
我收到以下 ts 錯誤:
Argument of type '{ id: number; property1: string; property2: string; reason: FirstReasonEnum; }' is not assignable to parameter of type 'never'.
The intersection 'FirstValuesType & SecondValuesType' was reduced to 'never' because property 'reason' has conflicting types in some constituents.(2345)
我該如何解決這個問題?
編輯:
這是游樂場的鏈接:
您的代碼假定model
是FirstClass
的實例,但類型表明它可能是FirstClass
的實例,也可能是SecondClass
的實例。 由於不清楚它是哪個,但setValues
需要知道,TypeScript 向您強調您傳遞的參數無效(或者我應該說可能無效)。 它不可能是有效的,因為它不能同時是FirstValuesType
和SecondValuesType
(這是FirstValuesType & SecondValuesType
的意思),因為reason
的類型不同。
解決它的最小更改方法是測試你必須查看它是否是FirstClass
實例,你可以這樣做,因為你已經使用了 class (不僅僅是接口)。 所以這修復了它:
if (model instanceof FirstClass) {
model.setValues(newValues);
} else {
// ...code here to do something with the `SecondClass` `model`
}
也就是說,您可能想重新考慮整體結構,但這實際上取決於具體情況,這看起來像是一個簡化的示例(適當簡化,以便提出問題)。 FirstClass
和SecondClass
以及FirstValuesType
和SecondValuesType
除了用於reason
的枚舉類型之外是相同的。 您可能會考慮在單個TheClass
和ValuesType
上使用泛型類型參數。 但這不會改變基本問題,即init
中的代碼假設 model 是一回事,而它可能是兩件事中的一個或另一個。
旁注:這部分init
代碼似乎有點可疑:
const model: TheClass<EnumType> = _model;
// ...
model.setValues(newValues);
model
常量和_model
參數指向相同的 object ,因此不創建不必要的附加標識符並直接使用_model
會更直接:
_model.setValues(newValues);
無論哪種方式,您都在修改傳入的 object。(如果您打算復制object,則需要執行復制操作。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.