[英]function as ambient module in TypeScript
How do I declare
an ambient module
that is a function
? 如何declare
作为function
的环境module
?
declare module "UUID" {
(seed?: number): string;
}
↑ Doesn't work. ↑不起作用。
You can also use declaration merging, if you need to specify properties on your function. 如果需要在函数上指定属性,也可以使用声明合并。
declare module UUID {
// ...
};
declare function UUID(seed?: number): string;
declare module "UUID" {
export = UUID;
}
None of this is recommended, but is inevitable when converting old js. 这些都不是推荐的,但在转换旧的j时是不可避免的。
declare module "UUID" {
function uuid(seed?: number): string;
export = uuid;
}
This is some text because code-only answers get flagged for attention! 这是一些文本,因为只有代码的答案会被标记为注意!
Derived from mk.'s answer, I had to arrange things a bit differently to make my compiler happy: 从mk。的答案中得出,我不得不安排一些不同的东西让我的编译器开心:
declare module 'UUID' {
namespace UUID {
// ...
}
function UUID(seed?: number): string;
export = UUID;
}
I must say it looks (a bit) more sane to me as well :) 我必须说它看起来(有点)对我更加理智:)
Actually, for some reason, exporting a function
directly as other answers here suggest seems to fail for me. 实际上,出于某种原因,直接导出function
作为其他答案在这里建议似乎对我来说失败了。 Inside of declare module
, I found I had to declare 在declare module
内部,我发现我必须声明
Then I could export the variable. 然后我可以导出变量。 For example, this should work (names changed, please comment if I have typos): 例如,这应该工作(名称已更改,如果我有拼写错误,请评论):
declare module 'UUID' {
interface UuidFunc {
(seed?: number): string;
}
const uuid:UuidFunc;
exports = uuid;
}
If I try the advice of the other answers, namely: 如果我尝试其他答案的建议,即:
declare module 'UUID' {
function uuid(seed?:number):string;
export = uuid;
}
and try to consume it with this code, I then get an error: 并尝试使用此代码使用它,然后我得到一个错误:
// TS2497: Module ''UUID'' resolves to a non-module entity and cannot be imported using this construct
import * as uuid from 'UUID';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.