为什么TypeScript将全局定义的导入添加为.default? [英] Why is TypeScript adding .default to a globally defined import?

查看:1240
本文介绍了为什么TypeScript将全局定义的导入添加为.default?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个外部库 thing.d.ts 文件,其中包含全局定义:

  declare var thing:ThingStatic; 
导出默认的东西;

我在TypeScript中引用了npm模块:

 从东西导入东西; 
...
thing.functionOnThing();

当我浏览TS(瞄准ES6)时,看起来像这样:

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

然后会抛出一个错误:


无法读取未定义的属性'functionOnThing'


为什么TypeScript添加 .default thing_1 functionOnThing()



ThingStatic 中没有名为的属性,默认 / code> c code code code code code code code code code code $是TypeScript添加属性,如何阻止它?

解决方案

 事情'; 

这行代码表示导入从模块'thing'导出并将其绑定到本地名称事物



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



您可能想要写的是

  import *作为东西的东西; 


I have an external library thing.d.ts file with a global definition inside:

declare var thing: ThingStatic;
export default thing;

I reference npm module in my TypeScript:

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

When I transpile the TS (targeting ES6) it looks something like this:

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

This then throws an error:

Cannot read property 'functionOnThing' of undefined

Why is TypeScript adding .default between thing_1 and functionOnThing()?

There is no property named default on ThingStatic, and no default property on the underlying JS object that the .d.ts file defines.

Why is TypeScript adding the property and how do I stop it?

解决方案

import thing from 'thing';

This line of code means "import the default export from the module 'thing' and bind it to the local name thing".

TypeScript does as you requested and accesses the default property of the module object.

What you probably meant to write was

import * as thing from 'thing';

这篇关于为什么TypeScript将全局定义的导入添加为.default?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆