3

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.

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

hmm, thanks, but the default property in my code should point to the run function which has a default property, which points to a run function which has the default property. It's just a circular reference, not sure what's wrong with what I have but maybe this solution will work, thanks!
I think what you are saying is that the default property is not attached to the run function until after declaration...that must be the problem. This solution seems to work, thanks.
Yep, you've got it.
2

If you weren't using a reserved word (default) you could do it like:

export function run() {
  // ...
}

export namespace run {
  export const DEFAULT = run;
}

But for what you seemed to be trying to do I think the simplest would be:

export function run() {
  // ...
}

export default run;

1 Comment

Thank you from the future! I needed to augment the types of some exported functions and didn't want to convert them to inline constants :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.