簡體   English   中英

Typescript 和 React - 基於通用值的條件道具

[英]Typescript and React - Conditional Props Based On Generic Value

我在Typescript遇到了一個問題,找不到解決辦法。

我有一個 React 組件,我想用不同的道具加載它,這取決於它的“類型”道具。

例如:

interface PropsA {
    a: string;
}

interface PropsB {
    b: string;
}

type Props<T extends string> = { type: T } & (T extends 'A' ? PropsA : PropsB);

class Component<T extends string> extends React.Component<Props<T>> {};

因此,預期的行為是 - 當類型道具等於“A”時,我希望組件允許(和必需)的道具僅為“a”而不是“b”。 但是,當我嘗試使用此組件並將其類型設置為“A”時,我可以毫無問題地使用“b”道具渲染它。

const App = () => {
    return (
        <Component type="A" b="whatever" />
    )
}

** NO ERROR!

但是,如果我稍微改變一下,以便條件道具將另一個道具內呈現,它將起作用:

type Props<T extends string> = { type: T } & { extraProp: T extends 'A' ? PropsA : PropsB };

class Component<T extends string> extends React.Component<Props<T>> {};

const App = () => {
    return (
        <Component type="A" extraProp={{ b: 'whatever' }} />
    )
}

** ERROR! (this is good, that means I can only use 'a' inside 'extraProp' like I wanted to.

此外,在道具類型中,如果我將交集更改為並集,它會起作用,但所需的道具“a”或“b”現在將是可選的,這不是我想要的。

為什么? 那是一些錯誤還是我遺漏了什么?

剛剛發現使用:

function Component<T extends string> (props: Props<T>) {
    return null;
}

代替:

class Component<T extends string> extends React.Component<Props<T>> {}

解決了問題。 但為什么? 它不應該也適用於 class 實現嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM