【问题标题】:TypeScript Definition File Cannot Find .d.tsTypeScript 定义文件找不到 .d.ts
【发布时间】: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


【解决方案1】:

这对我有用,在您项目的某些 d.ts 文件中,文件名不相关。 确保“messageformat”是节点模块的实际名称,否则您的打包程序将失败。

declare module "messageformat" {
    type Msg = (params: {}) => string;
    class MessageFormat {
        constructor(locale: string | string[] | Object);
        compile(messageSource: string): Msg;
    }
    export = MessageFormat;
}

现在,在其他一些模块中:

import MessageFormat from "messageformat";
const mf = new MessageFormat("en");
const thing = mf.compile("blarb");

【讨论】:

  • 你是对的,它有效。我有点疑惑,为什么官网上的TypeScript的例子没有像这个例子那样带引号的模块。
猜你喜欢
  • 1970-01-01
  • 2020-02-16
  • 2021-09-06
  • 2022-01-23
  • 2016-12-15
  • 2015-09-11
  • 2017-03-02
  • 2019-01-02
  • 2016-10-18
相关资源
最近更新 更多