小编Ste*_*Koo的帖子

forwardRef 的泛型错误:类型“IntrinsicAttributes”上不存在属性“ref”

将 forwardRef 与泛型一起使用时,我得到Property 'children' does not exist on type 'IntrinsicAttributes'or Property 'ref' does not exist on type 'IntrinsicAttributes'

https://codesandbox.io/s/react-typescript-0dt6d?fontsize=14

上面 CodeSandbox 链接中的相关代码复制到这里:

interface SimpleProps<T extends string>
  extends React.HTMLProps<HTMLButtonElement> {
  random: T;
}

interface Props {
  ref?: React.RefObject<HTMLButtonElement>;
  children: React.ReactNode;
}

function WithGenericsButton<T extends string>() {
  return React.forwardRef<HTMLButtonElement, Props & SimpleProps<T>>(
    ({ children, ...otherProps }, ref) => (
      <button ref={ref} className="FancyButton" {...otherProps}>
        {children}
      </button>
    )
  );
}

() => (
  <WithGenericsButton<string> ref={ref} color="green">
    Click me! // Errors: Property …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs

12
推荐指数
2
解决办法
3万
查看次数

条件属性的 TypeScript 实用程序类型(基于类型中其他属性的输入值)

我经常需要定义一个类型对象,其中只有当该类型的另一个属性是某个值时才接受属性键。

\n\n

一个简单的例子(在 React 的上下文中,但应该适用于任何情况)是我需要一个Button接受以下属性的类型对象:

\n\n
type Button = {\n  size: 'small' | 'large';\n  appearance: 'solid' | 'outline' | 'minimal';\n  isDisabled?: boolean;\n  hasFancyOutline?: boolean;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在,我实际上不希望类型接受hasFancyOutlineif appearanceis notoutlineisDisabledis false

\n\n

正确的方法是:

\n\n
type SharedButtonProps = {\n  size: 'small' | 'large';\n}\n\ntype NonOutlineButtonProps = SharedButtonProps & {\n  appearance: solid' | 'minimal';\n  isDisabled?: boolean;\n}\n\ntype OutlineButtonProps = SharedButtonProps & {\n  appearance: 'outline';\n  isDisabled: false;\n  hasFancyOutline?: boolean;\n}\n\ntype Button = NonOutlineButtonProps | OutlineButtonProps\n
Run Code Online (Sandbox Code Playgroud)\n\n

我想编写一个名为的速记实用程序类型ConditionalProps …

typescript reactjs typescript2.0

7
推荐指数
1
解决办法
2856
查看次数

标签 统计

reactjs ×2

typescript ×2

typescript2.0 ×1