reactjs - 如何使用 React 正确编写条件类型?

标签 reactjs typescript react-typescript

所以我正在尝试编写一种 Prop 类型格式,其中如果选择一个 Prop ,则另一个 Prop 将被丢弃。

type ButtonProps = {
    to: string,
} | {
    onClick: (() => void) 
};

export const BackButton = (props: ButtonProps) => {
  if(props.to != null) {
     //props {to} will be used hence no need for onClick
  }
  else {
    // {onClick} will be used over {to} 
  }
}

但它说

Property 'to' does not exist on type 'ButtonProps'. Property 'to' does not exist on type '{ onClick: () => void; }'.ts(2339`

如何使用 OR 格式化类型形状,以便在选择其中一个时,另一个将被丢弃。没有选项,所选择的 Prop 将是必需的。

最佳答案

我们需要使用类型保护来根据条件适当缩小类型范围。为此,我们需要对类型进行一点分割,以便在类型保护+可读性中进行断言。下面的 ButtonProps 与您的实现相同,但具有显式指定的联合元素。

第二件事是类型保护,在下面的代码片段中 isButtonWithTo 就是这样。它将类型缩小为联合中的选项之一。注意 is 关键字,它表示函数计算结果为 true 意味着什么,在本例中我是说,如果 isButtonWithTo 将返回 true,则参数的类型为 ButtonWithTo

type ButtonWithTo = {
    to: string,
}
type ButtonWithClick = {
    onClick: (() => void) 
}
// the same type as orginal but with explicit declarations of union elements
type ButtonProps = ButtonWithTo | ButtonWithClick 


const isButtonWithTo = (b: ButtonProps): b is ButtonWithTo  => 'to' in b // type guard

export const BackButton = (props: ButtonProps) => {
  if(isButtonWithTo(props)) {
     props // props have type ButtonWithTo
  } else {
    props // props have type ButtonWithClick
  }
}

关于reactjs - 如何使用 React 正确编写条件类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59069045/

相关文章:

javascript - 在 Angular 应用程序中将 FirebaseAuth.onAuthStateChanged 调用放在哪里?

javascript - 用 Jest 和 enzyme 进行测试。监视 react 组件的方法

javascript - 在点击 react 时切换 Font Awesome 图标

javascript - 覆盖 typescript 中的函数返回类型

reactjs - 类型 'File' 的参数不可分配给类型 'SetStateAction<string>' 的参数

reactjs - React 功能组件 Api 调用的 Jest Unit 测试用例

javascript - 在 Next.js 页面中检索子域

javascript - 如何在 Angular 指令中使用 React 自定义包

javascript - 如何从字符串中包含 <br/> 标签的字符串预填充文本区域

node.js 使用数组对事务进行 Sequelize 进行查询