Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force calling .toString() on an object when implicitly converted to a string

I'm looking for a way to automatically have an object's toString() method used in cases where it is implicitly converted to a string. For example, say you have this class:

class Dog {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  public toString(): string {
    return `${this.name} is my friend`;
  }
}

Then I would find that the second of the two assertions in this test will fail:

test.only("Dog", () => {
  const dog = new Dog("buddy");
  expect(dog.toString()).toBe("buddy is my friend");
  expect(dog as any as string).toBe("buddy is my friend"); // fails
});

I get the following error:

expect(received).toBe(expected) // Object.is equality
Expected: "buddy is my friend"
Received: {"name": "buddy"}

(Note: the assertion also fails if I use .toEqual rather than .toBe.)

I would like to make it so that this assertion passes, i.e. when I convert a Dog to a string by some implicitly method like this (as might happen in a TypeScript project that started its life as a JavaScript project).

Any suggestions on if this is possible? Is there some way to modify the Dog class to allow this?

like image 508
maxjeffos Avatar asked Jan 30 '26 17:01

maxjeffos


1 Answers

expect(dog as any as string).toBe("buddy is my friend");

as string only changes the type of the object in the typescript compiler. It doesn't do any actual type conversions.

If you check the outputted javscript, you will find plain old: expect(dog).toBe("buddy is my friend");

Just using .toString() explicitly may be your best bet

like image 50
thesilican Avatar answered Feb 03 '26 10:02

thesilican



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!