如何处理一个重载中存在而另一重载中不存在的属性?

Dun*_*une 2 overloading typescript reactjs

我使用 React 16 和 Typescript 3。我创建一个组件,根据属性是否设置返回按钮或链接。该组件可以获取toonClick属性,但不能同时获取两者。

在 TypeScript 存储库上发现了问题,它准确地描述了我的问题,并且似乎在 2.2 版本中修复了,但以某种奇怪的方式,它不起作用。

为此,我创建了接口并按如下方式使用它们:

interface GeneralProps {/* whatever here, it works */}
interface LinkProps extends GeneralProps { to: string }
interface ButtonProps extends GeneralProps { 
  onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void 
  // onClick might be as well undefined
}

function Button (props: LinkProps | ButtonProps): JSX.Element {
  const Component: AnyStyledComponent = props.to ? Link : Button
  return (
    <Component to={props.to} onClick={props.onClick}>
      {props.children}
    </Component>
  )
}
Run Code Online (Sandbox Code Playgroud)

或者,我也尝试这样编写这个函数:

function Button (props: LinkProps): JSX.Element
function Button (props: ButtonProps): JSX.Element {
  const Component: AnyStyledComponent = props.to ? Link : Button
  return (
    <Component to={props.to} onClick={props.onClick}>
      {props.children}
    </Component>
  )
}
Run Code Online (Sandbox Code Playgroud)

上面 Button 函数的第一个实现抛出两个错误,第二个实现仅抛出第一个错误:

类型“LinkProps | ”上不存在属性“to” ButtonProps'. 类型“ButtonProps”上不存在属性“to”。

类型“LinkProps | ”上不存在属性“onClick” ButtonProps'. 类型“LinkProps”上不存在属性“onClick”。

为了避免错误,我采用了一个愚蠢的解决方法:

function Button (props: LinkProps | ButtonProps): JSX.Element {
  const properties = Object.keys(props)
  const to = properties.find((el) => el === 'to')
  const Component: AnyStyledComponent = to ? Link : Button
  return (
    <Component {...props}>
      {props.children}
    </Component>
  )
}
Run Code Online (Sandbox Code Playgroud)

但是,这并不能解决我的问题,因为我仍然可以将toonClick属性传递给 Button 组件。

我的代码中是否存在某种阻止我实现目标的错误,我应该从不同的角度解决这个问题,还是这根本不可能做到?

Dun*_*une 5

感谢 jcalz 发布的帖子,我想出了一个解决方案,它实际上按照我的预期工作。我的解决方案是不同的(我使用接口,而不是类型),但是该线程让我想到使用 never 类型。我之前也使用过它,但是作为必需的属性,然后打字稿要求传递一个值,当你传递它时,打字稿要求删除它。从不键入的属性必须是可选的。

interface GeneralProps {/* whatever here, it works */}
interface LinkProps extends GeneralProps { 
  to: string
  onClick?: never
}
interface ButtonProps extends GeneralProps { 
  onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void 
  to?: never
}
function Button (props: LinkProps | ButtonProps): JSX.Element { ... }
Run Code Online (Sandbox Code Playgroud)

使用当前的解决方案,打字稿始终识别类型上存在的两个属性toonClick ,当我传递这两个属性时不会抛出错误,但当我传递这两个属性时会抛出错误。