javascript - TS 皮棉错误;类型 X 不可分配给类型 'IntrinsicAttributes & RefAttributes'
问题描述
我正在使用 webpack 开发一个 React 和 TypeScript 应用程序,并且我的每个 React 组件都遇到了完全相同的错误。错误总是这样:
Type X is not assignable to type 'IntrinsicAttributes & RefAttributes<any>'
我一直在寻找2天的解决方案。我认为我的 tsconfig.json 或我的 webpack 中可能有一些问题 - 两者都可以在底部的 GitHub 演示 repo 中找到。
示例 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.git
cd demo-tslint-error
npm install
npm run dev
我怎样才能避免这些错误?当我使用 Create React App TS bundler 时,我没有收到这些错误。我只是想传递一些简单的道具!!
解决方案
在您的tsconfig.json 中使用:
"moduleResolution": "node"
问题是使用"module": "es6"
似乎会导致模块解析策略更改为经典。这很烦人,因为文档中没有统一提及(他们指定发生这种情况AMD | System | ES2015
,但不是es6
)。
为了避免出现问题,我建议手动指定模块解析策略:
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,
// Explicitly force module resolution strategy to be node,
// to prevent "module": "es6" from changing it to classic.
"moduleResolution": "node"
},
"include": ["../src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
我还创建了一个拉取请求来应用此更改:https ://github.com/TJBlackman/demo-tslint-error/pull/1/commits/634ec9889096baca0676ddf3076c66e82addfdd8 (我sliftist
在 github 上)。
推荐阅读
- typescript - 打字稿索引签名类扩展类
- r - 重新列出各种深度的平面列表,保留类
- javascript - 实现一个breadthFirstSearch函数javascript
- sql - Teradata 中的不可见列
- android - 如何在 Cordova 上为 android 创建捆绑扩展?
- spring-security - RestTemplate 拦截器线程安全吗?
- asp.net - 是否可以使用接口扩展现有对象?
- leaflet - Nuxt Leaflet,更改瓷砖层请求不正确的瓷砖
- postgresql - RDS cloudwatch 指标“可用存储空间”不会通过 drop table 释放
- database - 在 DynamoDB 中预加入学生、班级和成绩