React TS报错:Type 'Error'无法赋值给类型'ReactNode'(ts2322)
TypeScript 向Message组件传error参数报类型不匹配错误
报错详情
Type 'Error' is not assignable to type 'ReactNode'.ts(2322)
Message.tsx(6, 3): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & Pick<Props, "children"> & InexactPartial<Pick<Props, "variant">> & InexactPartial<Pick<{ variant: string; }, never>>'
报错触发位置为loginScreen.tsx中渲染Message组件的代码行。
相关代码
loginScreen.tsx
return ( <FormContainer> <h1>Sign In</h1> {error && <Message variant="danger">{error} // 报错触发行</Message>} {loading && <Loader />} <Form onSubmit={submitHandler}> <Form.Group controlId="email"> <Form.Label>Email Address</Form.Label> <Form.Control type="email" placeholder="Enter email" value={email} onChange={(e) => setEmail(e.target.value)} ></Form.Control> </Form.Group> <Form.Group controlId="password"> <Form.Label>Password</Form.Label> <Form.Control type="password" placeholder="Enter password" value={password} onChange={(e) => setPassword(e.target.value)} ></Form.Control> </Form.Group> <Button type="submit" variant="primary"> Sign in </Button> </Form> <Row className="py-3"> <Col> New Customer?{" "} <Link to={redirect ? `/register?redirect=${redirect}` : "/register"}> Register </Link> </Col> </Row> </FormContainer>
Message.tsx
import { Alert } from "react-bootstrap"; interface Props { variant: string; children: ReactNode; } const Message = ({ variant, children }: Props) => { return ( <Alert variant={variant}> {children} </Alert> ); }; Message.defaultProps = { variant: "info", }; export default Message;
报错原因
- 第一处问题:
Message.tsx中使用了ReactNode类型,但未从react包导入该类型定义 - 第二处核心问题:
error是原生Error实例对象,不属于React可渲染的ReactNode类型范畴。ReactNode仅支持字符串、数字、JSX元素、null/undefined、布尔值、Fragment等可直接渲染的内容,原生Error对象无法直接作为子元素渲染。
修复方案
- 补全Message组件的类型导入,在
Message.tsx顶部添加ReactNode的导入语句:import type { ReactNode } from "react"; import { Alert } from "react-bootstrap"; - 渲染错误内容时传入Error对象的
message字符串属性,替换loginScreen.tsx中的报错行代码:
如果你的error类型存在联合类型(可能是字符串、null等),可以添加类型守卫兼容所有场景:{error && <Message variant="danger">{error.message}</Message>}{error && <Message variant="danger">{error instanceof Error ? error.message : error}</Message>}
内容的提问来源于stack exchange,提问作者Karan Sharma
相关产品推荐
相关产品推荐

