Search code examples
typescripttypescript-typingsnconf

Extending a typescript variable declaration


I want to use the nconf-yaml plugin with my Typescript project, but I don't know how to add it in my typings. In @types/nconf, the formats variable is declared as below:

export declare var formats: {
    json: IFormat;
    ini: IFormat;
};

How do I use declaration merging to add yaml, so that it will become:

export declare var formats: {
    json: IFormat;
    ini: IFormat;
    yaml: IFormat
};

Solution

  • I don't think you can do that. You can't modify the type of this variable because it is inlined! If the interface was declared separately, it would have been possible. So you can submit a pull request to their repo if you want :D

    If nconf typings was defined this way :

    export interface IFormats {
        json: IFormat;
        ini: IFormat;
    }
    export declare var formats: IFormats;
    

    You would have created a file index.d.ts containing:

    import * as nconf from "nconf";
    
    declare module "nconf" {
         export interface IFormats {
            json: nconf.IFormat;
            ini: nconf.IFormat;
            yaml: nconf.IFormat;
        }
    }
    

    It would have solved your problem.

    In the meantime you can still cast your variable before using it to ignore the type:

    (nconf.formats as any).yaml