How can I access a variable as both a function and an object instance with TypeScript?
log("something");
log.info("something");
I have tried many ways, like overriding prototype, but nothing seems to work:
var log = (...args) => {
console.log(...args);
};
log.prototype.info = (...args) => console.info(...args);
CodePudding user response:
You can definitely assign an .info
property to the function object that you assigned to log
in basic JavaScript.
log = (...args) => console.log(...args);
log.info = (...args) => console.info(...args);
log("something");
log.info("something");
In TypeScript, qualify as desired, or with : any[]
const log = (...args: any[]) => console.log(...args);
log.info = (...args: any[]) => console.info(...args);
log("something");
log.info("something");
Thanks @HereticMonkey for the TS Playground link. Note: the console.info
appears only in the developer tools, not in the TS playground's in-page log.
CodePudding user response:
This is very possible using Object.assign
type Log = {
(...args: any): void;
info: (...args: any) => void;
};
const log: Log = Object.assign((...args: any) => console.log(...args), {
info: (...args: any) => console.log('INFO:', ...args),
});
log('hello');
log.info('world');
Compiled:
"use strict";
const log = Object.assign((...args) => console.log(...args), {
info: (...args) => console.log('INFO:', ...args),
});
log('hello');
log.info('world');
You don't even need to create the Log
type if you don't want to. TypeScript will automatically infer the types of the objects you're passing to Object.assign
and create an intersection between them.
const log = Object.assign((...args: any) => console.log(...args), {
info: (...args: any) => console.log('INFO:', ...args),
});
log('hello');
log.info('world');