找不到 TypeScript 定义文件。d.ts

TypeScript Definition File Cannot Find .d.ts

上下文: 我正在尝试为我不是作者的 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;

Could not find a declaration file for module 'messageformat'. 'node_modules/messageformat/lib/messageformat.js' implicitly has an 'any' type.

第二次尝试(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;

Could not find a declaration file for module 'messageformat'. 'node_modules/messageformat/lib/messageformat.js' implicitly has an 'any' type.

第三次试试(from a GitHub question)

declare module "messageformat" {
    export type Msg = (params: {}) => string;
    export interface MessageFormat {
        new(message: string): any;
        compile: (messageSource: string) => Msg;
    }
}

Cannot use 'new' with an expression whose type lacks a call or construct signature.

代码: 三个暂定版本在这个 repo 中:https://github.com/MrDesjardins/importdefinitionfiles

有人可以指点我做错了什么吗?

这对我有用,在你项目的一些 d.ts 文件中,文件名不相关。 DO 确保 "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");