Inspection
You can customize the inspect behavior on Node.js and Deno.
// @see https://docs.deno.com/api/deno/~/Deno.inspect
const DENO_CUSTOM_INSPECT = Symbol.for("Deno.customInspect");
// @see https://nodejs.org/api/util.html
const NODEJS_UTIL_INSPECT_CUSTOM = Symbol.for("nodejs.util.inspect.custom");
// @see https://x.com/theMackabu/status/2044185796681637923
const ANT_SYMBOL_INSPECT = Symbol.inspect;
Usage
class A {
public constructor(
public x: number,
public y: number,
) {}
#inspect() {
return `x: ${this.x}, y: ${this.y}`;
}
[DENO_CUSTOM_INSPECT]() {
return this.#inspect();
}
[NODEJS_UTIL_INSPECT_CUSTOM]() {
return this.#inspect();
}
[ANT_SYMBOL_INSPECT]() {
return this.#inspect();
}
}
Once done, you’ll see the output of console.log is modified!
console.log(new A(1, 2));
// x: 1, y: 2
Going deeper
We can actually go deeper by monkey patching existing classes to provide more debug!
for (const SYMBOL_INSPECT of [
DENO_CUSTOM_INSPECT,
NODEJS_UTIL_INSPECT_CUSTOM,
ANT_SYMBOL_INSPECT,
]) {
Blob.prototype[SYMBOL_INSPECT] = function () {
return `Hello { world: ${this.size} }`;
};
}
console.log(new Blob());
// Hello { world: 0 }