Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

javascript - Why is TypeScript adding .default to a globally defined 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...