admin管理员组文章数量:1221398
function Foo({
children,
...rest
}: {
children: React.ReactNode;
/*rest: how do I type `rest`? */
}) {
return (
<span style={{ background: "red" }} {...rest}>
{children}
</span>
);
}
export default function App() {
return (
<div className="App">
<Foo style={{ background: "blue" }}>Hello CodeSandbox</Foo>
</div>
);
}
Here is the demo: =/src/App.tsx:50-412
Foo
is used to override the props that span
accepts. How do I type rest
in Foo
?
function Foo({
children,
...rest
}: {
children: React.ReactNode;
/*rest: how do I type `rest`? */
}) {
return (
<span style={{ background: "red" }} {...rest}>
{children}
</span>
);
}
export default function App() {
return (
<div className="App">
<Foo style={{ background: "blue" }}>Hello CodeSandbox</Foo>
</div>
);
}
Here is the demo: https://codesandbox.io/s/how-to-type-rest-huv2z?file=/src/App.tsx:50-412
Foo
is used to override the props that span
accepts. How do I type rest
in Foo
?
3 Answers
Reset to default 9You can't type the spread portion of the object directly, but you can add the necessary properties with the union type (&
).
In this case, the extra properties you want to allow are of type React.HTMLAttributes<HTMLSpanElement>
. So you end up with:
function Foo({
children,
...rest
}: {
children: React.ReactNode;
} & React.HTMLAttributes<HTMLSpanElement>) {
return (
<span style={{ background: "red" }} {...rest}>
{children}
</span>
);
}
As an aside, you can avoid manually typing the children
property using the React.FunctionComponent
type. This actually avoids the union definition and is a bit more idiomatic in React code.
const Foo: React.FunctionComponent<React.HTMLAttributes<HTMLSpanElement>> = ({
children,
...rest
}) => {
// ...
}
You can just use [x:string]: any;
like
function Foo({
children,
...rest
}: {
children: React.ReactNode;
[rest:string]: any;
}) {
return (
<span style={{ background: "red" }} {...rest}>
{children}
</span>
);
}
export default function App() {
return (
<div className="App">
<Foo style={{ background: "blue" }} id="example">Hello CodeSandbox</Foo>
</div>
);
}
You can use something like this as a type:
{
children: React.ReactNode;
/*rest: how do I type `rest`? */
} & HTMLProps<HTMLSpanElement>
本文标签:
版权声明:本文标题:javascript - TypeScript + React: How do I type a `rest` props that collects the rest of the props into an object and later sprea 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739328292a2158356.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论