Zander
Zander

Reputation: 2684

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

I would like my design-systems-utils module to include Typescript typings even though the source code is not written using Typescript (I have seen that others have done this).

I have already attempted this here, but it does not work. By the way, my module exports a 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
    }
}

I have also seen that I should be exporting this as a module, like so:

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;
    }
}

But that also does not work.

Any help would be greatly appreciated.

Upvotes: 0

Views: 862

Answers (1)

Aviad Hadad
Aviad Hadad

Reputation: 1717

In principal:

declare module "DesignSystem" { ...}

should be changed to the name of your npm module:

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

This is the way you tell typescript "Here are the types for when the user does 'import ... from design-systems-utils'". This is mostly useful when you need to extend library types from "outside".

However, since your package.json has types: src/index.d.ts field, we don't even need that. Typescript already knows what library your d.ts file provides definition for.

export default class DesignSystem {...}

should be enough.

Your first attempt declares a global class called DesignSystem. The general rule of thumb is that your d.ts should mirror you js structure. So if you do export default from js file, do it also from d.ts

(Also, thanks for providing definitions for your library, you make the world a better place)

Upvotes: 1

Related Questions