首页 > 解决方案 > 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:想自己运行代码吗?

  1. git clone https://github.com/TJBlackman/demo-tslint-error.git
  2. cd demo-tslint-error
  3. npm install
  4. npm run dev

我怎样才能避免这些错误?当我使用 Create React App TS bundler 时,我没有收到这些错误。我只是想传递一些简单的道具!!

标签: javascriptreactjstypescript

解决方案


在您的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 上)。


推荐阅读