typescript - 由于 'no compatible call signatures',无法在 typescript 中使用类名

标签 typescript

运行相关的 yarn add 命令后,packages.json 中有以下新行:

"@types/classnames": "^2.2.7",
"classnames": "^2.2.6",

然后我在我的 typescript 文件中添加了这些行:

import * as classnames from 'classnames';
...
            <div className={classnames('normal', 'on')}>

现在我收到这个错误

Type error: Cannot invoke an expression whose type lacks a call signature. Type '{ default: ClassNamesExport; }' has no compatible call signatures. TS2349

我的 tsconfig.json 的内容

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "experimentalDecorators": true
  },
  "include": [
    "src"
  ]
}

我该如何修复这个错误?

最佳答案

当您执行 import * as X from 'x' 时,您将获得一个模块 namespace 对象。它是一个不可变对象(immutable对象),不可调用。

由于 classnames 是一个 commonjs 模块,您需要在 tsconfig.json 中设置 esModuleInterop: true 并执行 import classnames来自“类名”,

或者您可以使用旧语法导入它:import classnames = require('classnames')

推荐使用esModuleInterop

关于typescript - 由于 'no compatible call signatures',无法在 typescript 中使用类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54500943/

相关文章:

javascript - 使用数组和多维对象以 Angular 显示 API 结果

javascript - Typescript 中的 XHR 拦截器

TypeScript:从可区分的联合中推断类型以创建 map ?

typescript - 在 Typescript 中,如何检查字符串是否为数字

angular - 访问 FormArray 中的对象属性并更新 Angular 4 中的值

angular - 必需的 Input() 参数仍然发出 "has no initializer"错误

typescript - 在类中使用泛型类型 - 类型 T 不满足约束

angular - 子组件不更新父路由更改

TypeScript 建议对象中的键

typescript - 如何键入一个函数来检查参数是否扩展类型参数并返回 typescript 中的参数?