【问题标题】:error TS2318: Cannot find global type 'Object'错误 TS2318:找不到全局类型“对象”
【发布时间】:2018-11-16 04:20:33
【问题描述】:

很简单的项目,没有tsconfig.json只用命令行:

tsc --jsx react --target es6 --lib dom src/lib/Fetch.tsx

我收到以下错误,但我不明白为什么,这些类型在任何地方都有字面定义,特别是在 lib.es6.d.ts 中,我相信它包含在 --target es6

error TS2318: Cannot find global type 'Array'.
error TS2318: Cannot find global type 'Boolean'.
error TS2318: Cannot find global type 'Function'.
error TS2318: Cannot find global type 'IArguments'.
error TS2318: Cannot find global type 'Number'.
error TS2318: Cannot find global type 'Object'.
error TS2318: Cannot find global type 'RegExp'.

安装以下依赖项

"dependencies": {
  "@types/react-dom": "^16.0.6",
  "@types/react": "^16.3.16",
  "react": "^16.4.0",
  "react-dom": "^16.4.0"
},
"devDependencies": {
  "@types/node": "^10.3.1",
  "typescript": "^2.9.1"
}

已解决

找出我的问题。在本地安装了 typescript,但正在运行全局安装的旧版本 typescript。当我通过 npm 脚本运行 tsc 时,它使用以下命令进行编译:

tsc --jsx react --target es6 --module commonjs src/lib/Fetch.tsx

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    dom 仅包含浏览器特定 DOM 元素的定义。您需要包含 es* 库之一,其中包含编译所需的核心 es 类型。一旦你指定了 --lib 选项,你必须包含所有必要的类型,编译器将不再包含任何基于你的目标的库:

    tsc --jsx react --target es6 --lib es2015,dom src/lib/Fetch.tsx
    

    或者,如果您实际上不只是使用默认库,则可以完全省略该选项:

    tsc --jsx react --target es6 src/lib/Fetch.tsx
    

    【讨论】:

    • 不幸的是,这些都不起作用。他们都抱怨 AbortController、csstype(在 @types/react/index.d.ts 中)以及有关 RequestInt 和信号的一些东西。我构建了一个更孤立的示例,将用详细信息更新我的问题。
    • @AustinFrance 例如尝试使用更高版本的 es 库版本 es2018。但是这些内置类型没有找到的具体错误是由于缺少默认的es库造成的。
    • 我发现了问题所在。当我在本地安装了较新版本时,我正在运行全局安装的较旧版本的打字稿。如果我通过 npm 运行 tsc,我的原始代码可以正常工作,但我还必须包含 --module commonjs 以防止 @types/react 抱怨。
    • 将您的答案标记为答案,因为仅考虑问题的上下文,添加 --lib dom 确实会产生看到的错误,而删除 --lib dom 会纠正该错误,正如您所建议的。
    猜你喜欢
    • 2016-12-21
    • 2017-09-27
    • 2015-12-29
    • 2020-07-07
    • 2017-03-25
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多