簡體   English   中英

TS 皮棉錯誤; 類型 X 不可分配給類型 'IntrinsicAttributes &amp; RefAttributes<any> '</any>

[英]TS Lint Error; Type X is not assignable to type 'IntrinsicAttributes & RefAttributes<any>'

我正在使用 webpack 開發 React 和 TypeScript 應用程序,並且我的每個 React 組件都遇到完全相同的錯誤。 錯誤總是這樣:

Type X is not assignable to type 'IntrinsicAttributes & RefAttributes<any>'

我一直在尋找2天的解決方案。 我認為我的 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>'. 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>' 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 示例回購:想自己運行代碼嗎?

  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 時,我沒有收到這些錯誤。 我只是想傳遞一些簡單的道具!!

在您的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 (我是 github 上的sliftist )。

有關更多信息,請閱讀這些文檔

關於模塊做什么的文檔

允許的模塊選項和值的文檔

webpack 上的文檔反應基本配置

使用module:"commonJS"

要編譯,我們必須在命令行上指定一個模塊目標。 對於 Node.js,使用 --module commonjs; 對於 require.js,使用 --module amd

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM