【问题标题】:In React Typescript how to define type for ...rest parameter for native html elements?在 React Typescript 中,如何为原生 html 元素定义 ...rest 参数的类型?
【发布时间】:2019-09-25 04:48:48
【问题描述】:

我正在尝试过滤一些道具,然后将其余道具传递给原生 html 元素,如下所示:

const Placeholder = (
  display: boolean,
  ...rest: Array<React.LabelHTMLAttributes<HTMLLabelElement>>
) => <label {...rest} />

问题是这给了我这个错误:

Type '{ length: number; toString(): string; toLocaleString(): string; pop(): LabelHTMLAttributes<HTMLLabelElement> | undefined; push(...items: LabelHTMLAttributes<HTMLLabelElement>[]): number; ... 28 more ...; flat<U>(this: U[][][][][][][][], depth: 7): U[]; flat<U>(this: U[][][][][][][], depth: 6): U[]; flat<U>(this: U[]...' has no properties in common with type 'DetailedHTMLProps<LabelHTMLAttributes<HTMLLabelElement>, HTMLLabelElement>'.ts(2559)

如何为 Typescript / React 中的 label 等原生 html 元素定义 ...rest 参数的类型?

【问题讨论】:

  • 试试Array&lt;React.LabelHTMLAttributes&lt;T&gt;&gt;

标签: javascript reactjs typescript


【解决方案1】:

label的类型为:React.DetailedHTMLProps&lt;React.LabelHTMLAttributes&lt;HTMLLabelElement&gt;, HTMLLabelElement&gt;

因此,依靠这一点,这样的事情应该可以工作:

interface Props
  extends React.DetailedHTMLProps<
    React.LabelHTMLAttributes<HTMLLabelElement>,
    HTMLLabelElement
  > {
  display: boolean;
}

const Placeholder = ({ display, ...rest }: Props) => <label {...rest} />;

const App = () => <Placeholder display htmlFor="form" />;

另外,请注意,由于第一个参数是 props,因此被解构为对象(因此 ...rest 是作为对象的剩余道具),而不是数组。

【讨论】:

  • 优秀。我经常发现自己在寻找类似这些类型的任务。您如何在没有大量试验和错误的情况下确切知道要使用哪些类型?
  • 使用 Codesandbox 或 VSCode,将鼠标悬停在 &lt;label {...rest} /&gt; 中的 label 上会显示类型。此外,标签上的cmd + click(在 VSCode 中的 macOS 上)将打开类型定义。
猜你喜欢
  • 1970-01-01
  • 2019-02-09
  • 1970-01-01
  • 2021-12-22
  • 2023-03-28
  • 2020-08-05
  • 2018-10-24
  • 2020-11-03
  • 1970-01-01
相关资源
最近更新 更多