【发布时间】:2018-09-16 18:19:39
【问题描述】:
上下文:我正在尝试为我不是作者的library 创建一个定义文件。在使用我创建的定义文件时,TypeScript 提到它找不到定义文件。
我已经尝试了几件事,这里是最后三个:
首先尝试(inspired by a similar library d.ts):
declare class MessageFormat {
constructor(message: string);
compile: (messageSource: string) => Msg;
}
export type Msg = (params: {}) => string;
export default MessageFormat;
找不到模块“messageformat”的声明文件。 'node_modules/messageformat/lib/messageformat.js' 隐含了一个 'any' 类型。
第二次尝试(from TypeScript's example to write d.ts)
declare class MessageFormat {
constructor(message: string);
compile: (messageSource: string) => MessageFormat.Msg;
}
declare namespace MessageFormat {
type Msg = (params: {}) => string;
}
export = MessageFormat;
找不到模块“messageformat”的声明文件。 'node_modules/messageformat/lib/messageformat.js' 隐含了一个 'any' 类型。
第三次尝试 (from a GitHub question)
declare module "messageformat" {
export type Msg = (params: {}) => string;
export interface MessageFormat {
new(message: string): any;
compile: (messageSource: string) => Msg;
}
}
不能将“new”与类型缺少调用或构造签名的表达式一起使用。
代码: 三个暂定代码在这个 repo 中:https://github.com/MrDesjardins/importdefinitionfiles
有人可以告诉我我做错了什么吗?
【问题讨论】:
-
你如何导入模块/试图用它调用
new? -
@RyanCavanaugh 第三方模块来自
npm并使用import MessageFormat from "messageformat";导入 -
不知道为什么在上一个示例中突然切换到带有 new(...) 方法的接口。使用
constructor将其更改为class是正确的。此外,查看源构造函数签名应该是:constructor(locale: string|string[]|Object)并且 Object 也应该替换为适当的接口。 -
另外,在环境模块声明中的普通类型定义中不需要
export关键字。默认情况下,所有内容都被导出和声明。 -
最后你需要的一个导出,因为
MessageFormat是这个模块的默认导出是export = MessageFormat;
标签: typescript typescript-typings typescript2.0