Search code examples
javascripttypescripttypescript2.2

Adding property to function with TypeScript


Say I have a function expression called run:

let run = function(){


};

I want to add a property called "default" to this run function, a reference to itself.

run.default = run;

this is to support multiple module export formats in JS.

I hear the best way to do this is with a namespace.

Here is my actual code:

namespace run {

  export interface Run {
    (paths: Array<string>, opts: run.IOpts, cb: Function): void
    default: Run;
  }

  export interface IOpts {
    babelExec?: string,
    all?: boolean
  }
}


  const run : run.Run = function (paths: Array<string>, opts: run.IOpts, cb: Function): void {

    //....

  }


run.default = run;
export = run;

but I get this warning:

enter image description here

Does anyone know why that error message occurs?

As you can see, TS thinks I don't have the property typings for the default property, but I am pretty sure I do with the namespace declaration...or not? So confused by this error - the error/warning seems incorrect.


Solution

  • The error is effected because the function you are assigning to default does not have a default property - it's just a function.

    You've declared default as Run, so anything assigned to it will also have to have a default property.

    You could either make default optional:

    default?: Run;
    

    Or could declare it as a function:

    default: (paths: Array<string>, opts: run.IOpts, cb: Function) => void;