[英]How to declare a module in TypeScript with an object as default export
In a TypeScript project, I would like to use a third-party library that does not provide type definitions. 在TypeScript项目中,我想使用不提供类型定义的第三方库。 So I need to come up with my own module declaration. 因此,我需要提出自己的模块声明。 What the module basically exports looks like this: 模块基本上导出的内容如下所示:
const foo = {
bar () {
return 23;
}
};
module.exports = foo;
So, the question now is how to come up with the module declaration. 因此,现在的问题是如何提出模块声明。 First of all, it's obvious that the module uses a default
export, not a named one. 首先,很明显,该模块使用default
导出,而不是命名导出。 This default export is an object, which has methods. 此默认导出是具有方法的对象。 So I tried this: 所以我尝试了这个:
declare module 'foo' {
export default {
bar(): number;
};
}
However, the TypeScript compiler complains that: 但是,TypeScript编译器抱怨:
The expression of an export statement must be an identifier or a qualified name in an ambient context. 在环境上下文中,export语句的表达式必须是标识符或限定名称。
What does this mean? 这是什么意思? Using bar
, I have used an identifier, haven't I? 使用bar
,我使用了标识符,不是吗? And what does "qualified name in an ambient context" mean? “环境中的合格名称”是什么意思?
Using bar, I have used an identifier, haven't I? 使用bar,我使用了标识符,不是吗?
The error is talking about the object of the export clause. 错误是在谈论export子句的对象。 While you have used bar
as an identifier, specifically as a method name, you are not exporting that identifier, you are exporting an object literal contains it. 当您使用bar
作为标识符,特别是作为方法名称时,您没有在导出该标识符,而是在导出包含它的对象文字。
In 在
declare module 'foo' {
export default {bar(): number};
}
the identifier bar
refers to a method of the exported value not the exported value itself. 标识符bar
指的是导出值的方法,而不是导出值本身。
To correct this, write 要更正此问题,请写
declare module 'foo' {
const foo: {bar(): number};
export default foo;
}
A qualified name is a name that referred to by qualifying its name with its enclosing scope as in ab
合格名称是通过用其包围范围对名称进行限定来引用的名称,如ab
declare module 'foo' {
namespace ns {
const foo: {bar(): number};
}
export default ns.foo;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.