如何将打字稿类型添加到导出 class 的 NPM 模块?

How to add typescript typings to NPM module that exports a class?

我希望我的 design-systems-utils 模块包含 Typescript 类型,即使源代码不是使用 Typescript 编写的(我看到其他人已经这样做了)。

我已经尝试过 here,但它不起作用。顺便说一下,我的模块导出一个 class...

declare class DesignSystem {
    constructor(system: object, options?: object);
    multiply(initial: number, multiplier: number): any;
    get(val: string): any;
    bp(bp: string): any;
    z(z: string): any;
    fontSize(size: string|number, toPxl?: boolean): string;
    fs(size: string|number, toPxl?: boolean): string;
    spacing(index: number): string;
    space(index: number): string;
    toPx(value: number, base: number, unit?: string): string;
    pxTo(value: number, base: number): string;
    color(hue:string, value:string): string;
    designSystem: object;
    interface options {
        defaultUnit: string,
        useModularScale: boolean,
        fontSizeUnit: string
    }
}

我还看到我应该将其导出为一个模块,如下所示:

declare module "DesignSystem" {
    export default class DesignSystem {
        constructor(system: object, options?: object);
        /*~ Multiply two items together */
        multiply(initial: number, multiplier: number): any;
        get(val: string): any;
        bp(bp: string): any;
        z(z: string): any;
        fontSize(size: string|number, toPxl?: boolean): string;
        fs(size: string|number, toPxl?: boolean): string;
        spacing(index: number): string;
        space(index: number): string;
        toPx(value: number, base: number, unit?: string): string;
        pxTo(value: number, base: number): string;
        color(hue:string, value:string): string;
        designSystem: object;
    }
}

但这也行不通。

如有任何帮助,我们将不胜感激。

原则上:

declare module "DesignSystem" { ...}

应更改为您的 npm 模块的名称:

declare module "design-systems-utils" { ...}

这就是你告诉打字稿的方式 "Here are the types for when the user does 'import ... from design-systems-utils'"。当您需要从 "outside" 扩展库类型时,这非常有用。

但是,由于您的 package.json 有 types: src/index.d.ts 字段,我们甚至不需要它。 Typescript 已经知道您的 d.ts 文件为哪个库提供了定义。

export default class DesignSystem {...}

应该够了。

您的第一次尝试声明了一个名为 DesignSystem 的 global class。一般的经验法则是你的 d.ts 应该反映你的 js 结构。所以如果你从 js 文件做 export default,也从 d.ts

(另外,感谢您为您的图书馆提供定义,您让世界变得更美好)