ccnokes ccnokes - 2 months ago 5
TypeScript Question

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'.
?

Answer

You would write it this way:

function log(msg: string) {

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

export default log;
Comments