typescript 带有默认可选值的react props的条件类型

rkue9o1l  于 2023-10-22  发布在  TypeScript
关注(0)|答案(1)|浏览(120)

我想要有条件props类型
当我试图传递一个默认值给我的可选prop时,它在条件类型中,类型中断

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>
  )
}

为什么当我传递一个默认值时,逻辑就中断了?

gdrx4gfi

gdrx4gfi1#

你的代码是部分的,我不确定CardProps是什么,我做了一个缩小的例子,似乎工作。你可以找到here

相关问题