javascript - 为什么 TypeScript 将 .default 添加到全局定义的导入中?

标签 javascript typescript ecmascript-6 typescript-typings

我有一个外部库 thing.d.ts 文件,里面有一个全局定义:

declare var thing: ThingStatic;
export default thing;

我在我的 TypeScript 中引用了 npm 模块:

import thing from 'thing';
...
thing.functionOnThing();

当我转译 TS(针对 ES6)时,它看起来像这样:

const thing_1 = require("thing");
...
thing_1.default.functionOnThing();

这会抛出一个错误:

Cannot read property 'functionOnThing' of undefined

为什么 TypeScript 在 thing_1functionOnThing() 之间添加 .default

ThingStatic 上没有名为 default 的属性,在 .d. 的基础 JS 对象上也没有名为 default 的属性。 ts 文件定义。

为什么 TypeScript 添加该属性,我该如何停止它?

最佳答案

import thing from 'thing';

这行代码的意思是“从模块'thing'导入default导出并将其绑定(bind)到本地名称东西”。

TypeScript 按照您的要求执行并访问模块对象的 default 属性。

你可能想写的是

import * as thing from 'thing';

关于javascript - 为什么 TypeScript 将 .default 添加到全局定义的导入中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41148057/

相关文章:

javascript - Ajax 请求 asp.net mvc Controller 返回 500 - 内部服务器错误

Angular 2 - 单击父元素时防止单击子元素?

javascript - 返回此返回未定义

javascript - 单击本身更改按钮背景颜色

javascript - SQL 中无法识别禁用的文本字段值

javascript - 分类数据的 Mapbox 数据驱动样式 - 如何将表达式与数组输入匹配?

reactjs - 每当我在应用程序中执行某些操作时,React 都会抛出数千个 TypeError

javascript - 将 Children 属性传递给 React Memo 组件

ecmascript-6 - es6 中解构获取数组的最后一个元素

javascript - 组合两个复杂对象不起作用 : Javascript