Short Form for toString() and valueOf() in Anonymous Objects

I can specify linearized values for anonymous objects like this:

const foo = {
  a: 123,  
  b: "xyz", 
  valueOf() {return this.a;},
  toString() {return this.b;} 
} 

console.log(+foo); // 123
console.log(`${foo}`); // xyz

or with arrow functions:

const foo = {
  a: 123,  
  b: "xyz", 
  valueOf: () => this.a, 
  toString: () => this.b
} 

console.log(+foo); // 123
console.log(`${foo}`); // xyz

I wish there was a concise way to do this without having to explicitly name valueOf and toString. Iʼm not sure how that would look though.

const foo = {
  a: 123,  
  b: "xyz"
} => [+a, `$b`];

const foo = {
  a: 123,  
  b: "xyz"
} => a; // only valueOf() 

const foo = {
  a: 123,  
  b: "xyz"
} => b; // only toString() 

const foo = {
  a: 123,  
  b: "xyz"
} => {
  valueOf: a, 
  toString: b
} 

I don't see what's wrong with using method syntax for methods? (Notice the arrow function example doesn't actually work).
Why are you defining object literals with valueOf/toString methods often enough that you wish there was a special syntax for it? I can't see that happen in regular code - if you have that many object literals, use a factory function or even class for it.

And even if they're all different, you can factor out the shared parts into a helper function, like

function withToPrimitive(obj, valueProp, stringProp) {
  if (valueProp) obj.valueOf = () => obj[valueProp];
  if (stringProp) obj.toString = () => obj[stringProp];
  return obj;
}

const foo = withToPrimitive({
  a: 123,
  b: "xyz",
}, "a", "b");
2 Likes
const abobj = 
  valueOf() {return this.a;},
  toString() {return this.b;} 
} 

const foo = {
  __proto__ : abobj,
  a: 123,  
  b: "xyz", 
} 

const var = {
  __proto__ : abobj,
  a: 456,  
  b: "abc", 
} 

etc.

Itʼs mostly sugar for quick and dirty code.

At least for simple cases, I could also envision markers like so:

const foo = {
  a: 123 __value,  
  b: "xyz" __string, 
}  

Adding new syntax to ECMAScript has a high cost, I doubt they'll add more syntactic sugar that's only useful in quick'n'dirty code.