【发布时间】:2020-06-21 06:33:29
【问题描述】:
我正在使用 webpack 开发一个 React 和 TypeScript 应用程序,并且我的每个 React 组件都遇到完全相同的错误。错误总是这样:
Type X is not assignable to type 'IntrinsicAttributes & RefAttributes<any>'
我这两天一直在寻找解决方案。我认为我的 tsconfig.json 或我的 webpack 中可能有一些问题 - 两者都可以在底部的 GitHub 演示库中找到。
示例 1:
假设我有这个组件:
export const Container = ({children}) => {
return (
<Container>
{children}
</Container>
);
}
上述组件的错误会抱怨 children 道具:
TS2322: Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes & RefAttributes<any>'.
示例 2
假设我有这个组件:
export const Title = ({text, color}) => {
return (
<h1 style={{color: color}}>{text}</h1>
);
}
然后错误抱怨这两个道具:
TS2322: Type '{ text: string; color: string; }' is not assignable to type 'IntrinsicAttributes & RefAttributes<any>'
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": false,
"lib": ["es6", "dom"],
"noImplicitThis": true,
"strictNullChecks": true,
"module": "es6",
"target": "es6",
"jsx": "react",
"allowJs": true,
"allowSyntheticDefaultImports": true
},
"include": ["../src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
Github Example Repo:想自己运行代码吗?
git clone https://github.com/TJBlackman/demo-tslint-error.gitcd demo-tslint-errornpm installnpm run dev
如何避免这些错误?当我使用 Create React App TS bundler 时,我没有收到这些错误。我只是想传递一些简单的道具!!
【问题讨论】:
标签: javascript reactjs typescript