具有默认可选值的 React props 的条件类型

问题描述 投票:0回答:1

我想要有条件的道具类型

当我尝试将默认值传递给位于条件类型内部的可选属性时,类型会中断

export type ChatBase = {
  id: string;
  title: string;
}

type ChatCardProps = CardProps &
  (
    | {
        chat: ChatBase & { createdBy: { displayName: string } };
        hideCreator?: false;
      }
    | {
        chat: ChatBase;
        hideCreator: true;
      }
  );

const Chat = ({ title, chat, hideCreator = false }: ChatCardProps) => {
  return (
    <View>
      <Text>{title}</Text>
      {!hideCreator && <Text>{chat.createdBy.displayName}</Text>}
      //                            ^? createdBy?: { displayName: string; } | undefined
    </View>
  )
}

const Chat = ({ title, chat, hideCreator }: ChatCardProps) => {
  return (
    <View>
      <Text>{title}</Text>
      {!hideCreator && <Text>{chat.createdBy.displayName}</Text>}
      //                            ^? createdBy?: { displayName: string; }
    </View>
  )
}

为什么当我传递默认值时逻辑会中断?

reactjs typescript react-props
1个回答
-1
投票

您的代码是部分的,我不确定

CardProps
是什么,我做了一个缩小的示例,似乎可行。您可以在这里找到它。

© www.soinside.com 2019 - 2024. All rights reserved.