Reputation: 233
I'm just learning TypeScript and getting stuck trying to add some methods to the DOM or other existing objects. As an example, I'm trying to add a method I can call to use color in console logging. However, I'm getting a couple of TypeScript errors.
Object.defineProperties(console, {
redLog: function(msg: string) { console.log(`%c${msg}`, 'color:red'); //TS error: Type '(msg: string) => void' has no properties in common with type 'PropertyDescriptor'.
},
});
console.redLog("This should print red") //TS error: Property 'redLog' does not exist on type 'Console'.
Any idea what I'm doing wrong? I'm not sure how to leverage interfaces or whatever TS approach would be needed to allow me to add this console.redLog() method. Thanks for any help!
Upvotes: 0
Views: 745
Reputation: 25790
When modifying objects that are already defined in TypeScript, you need two things:
To tell TypeScript it can expect a method called redLog
on the console
, you need to find the type/interface that stores the definition of console
and augment it.
In this case, console
is described by the Console
interface defined in the global scope. To add a property to that interface, you need to enter the scope in which it exists and define it again. Your definition will be merged with the existing one.
This definition will enter the global scope (declare global
) and re-define the Console
interface:
declare global {
interface Console {
redLog(msg: string): string;
}
}
Put that definition in your project, and your global Console
will be augmented!
Complete solution
declare global {
interface Console {
redLog(msg: string): void;
}
}
Object.defineProperties(console, {
redLog: {
value: function (msg: string) {
console.log(`%c${msg}`, 'color:red')
},
}
});
Upvotes: 1