Why, when using Symbol.toPrimitive, do we have to return a primitive of the same type as the hint? For example, when using valueOf() and toString(), we can return for example a string for the "number" hint, or for example a number for the "string" hint. But in Symbol.toPrimitive this does not work, as if after the return there is another typecast.
let user = {
name: 'John',
money: 1000,
[Symbol.toPrimitive](hint) {
return hint == 'string' ? 123 : `this.money`;
},
};
alert(user); // 123
alert(+user); // NaN
Here we get 123 for string hint and NaN for number hint.
If we do it like this:
let user = {
name: 'John',
money: 1000,
toString() {
return 123;
},
valueOf() {
return '123';
},
};
alert(user); // 123
alert(+user); // '123'
As a result, we will get 123 for string hint and '123' for number hint.