ccnokes
ccnokes

Reputation: 7105

How do I type a function object with additional functions attached as properties?

In TypeScript, I'd like to create a module that exports a function that has additional functions added to it, like so:

export default function log(msg: string) {
    console.log(msg);
}

//Property 'warn' does not exist on type '(msg: string) => void'.
log.warn = function(msg: string) {
    console.warn(msg);
};

The usage of this could look like:

log('test');
log.warn('test');

How do I tell TypeScript that my function object has additional properties on it so that it doesn't throw Property 'warn' does not exist on type '(msg: string) => void'.?

Upvotes: 1

Views: 139

Answers (2)

user663031
user663031

Reputation:

Like this:

const log: { (msg: string): void; warn?: Function; } = function (msg: string) {
  console.log(msg);
}

log.warn = function (msg: string) { console.warn(msg); };

export default log;

In other words, a function type with properties can be declared as

type FuncWithProp = {
  (FUNC_PARAMS): FUNC_RETURN_TYPE;
  YOUR_PROP_HERE: SOME_TYPE;
};

If you want to type the attached function more closely to take strings and output them, and allow additional ones, then

type Logger = {
  (msg: string): void;
  warn?: Logger;
  error?: Logger;
};

const log: Logger = function...
log.warn = function...
export default log;

Upvotes: 1

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220944

You would write it this way:

function log(msg: string) {

}
namespace log {
  export function warn(omen: string) { }
}

export default log;

Upvotes: 2

Related Questions