![](/img/trans.png)
[英]Types of property 'type' are incompatible. Problem with Typescript union types
[英]Union of types was reduced to 'never' breaks typing: Type was reduced to 'never' because property has conflicting types in some constituents
我有一個從基本接口擴展的類型集合:
interface BaseType {
id: number;
titleText: string;
}
export enum ComponentType {
AUDIO = 'type_audio',
ARTICLE = 'type_article',
BASIC = 'type_basic',
DOWNLOAD = 'type_download',
LINK = 'type_link',
QUOTE = 'type_quote',
VIDEO = 'type_video',
}
export interface BasicComponent extends BaseType {
type: ComponentType.BASIC;
}
export interface QuoteComponent extends BaseType {
type: ComponentType.QUOTE;
subtitle?: string;
}
export interface LinkComponent extends BaseType {
type: ComponentType.LINK | ComponentType.ARTICLE;
subtitle?: string;
}
export interface DownloadComponent extends BaseType {
type: ComponentType.DOWNLOAD;
}
export interface AudioComponent extends BaseType {
type: ComponentType.AUDIO;
mediaType: MediaType.AUDIO;
mediaRef: Reference;
configRef: Reference;
}
export interface VideoComponent extends BaseType {
type: ComponentType.VIDEO;
mediaType: MediaType.VIDEO;
mediaRef: Reference;
configRef: Reference;
}
但是當我創建一個可以是這些組件類型中的任何一種的類型,並使用 switch case 將它們分配給React
組件時,我得到一個錯誤。
export type Component =
| BasicComponent
| AudioComponent
| DownloadComponent
| LinkComponent
| VideoComponent
| QuoteComponent;
const getChild = () => {
switch (props.type) {
case ComponentType.AUDIO:
return AudioComponent;
case ComponentType.DOWNLOAD:
return DownloadComponent;
case ComponentType.ARTICLE:
case ComponentType.LINK:
return LinkComponent;
case ComponentType.QUOTE:
return QuoteComponent;
case ComponentType.VIDEO:
return VideoComponent;
case ComponentType.BASIC:
return BasicComponent;
}
};
const Component = getChild();
return <Component {...props} />;
// ^^^
// The intersection 'IntrinsicAttributes & AudioTeaser & { children?: ReactNode; } &
// DownloadTeaser & LinkTeaser & QuoteTeaser & VideoTeaser & BasicTeaser' was reduced
// to 'never' because property 'type' has conflicting types in some constituents.
// Type props is not assignable to type 'never'.
這將需要類似相關類型的東西,其中打字稿可以知道Component
和props
的類型是相關的。 目前這並不存在。
發生的情況是Component
最終成為所有可能組件的聯合。 由於Component
可以是任何一個有效的組件,因此只有使用滿足所有可能的組件 props 的 props(因此所有可能的 props 的交集)來創建這個組件才是安全的。 由於 props 是互斥的,你最終會在這個交集的某處得到一個never
(即沒有可能值的類型)。
最簡單的解決方案是使用類型斷言將組件的聯合轉換為一個接受 props 的組件,該 props 是所有可能的 props 的聯合。 現在這通常不安全,但在這種情況下,我們告訴打字稿我們更了解:
const Component = getChild() as React.FC<Component>;
return <Component {...props} />;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.