DEV Community

loading...

Discussion on: Using JavaScript Symbol.toStringTag for objects types description

Collapse
ninofiliu profile image
Nino Filiu

Nice, I didn't know about this!

But I wouldn't trust this trick for type-safety checking

const user = {
  name: 'John',
  [Symbol.toStringTag]: 'User',
};
delete user.name;
if (user[Symbol.toStringTag] === 'User') {
  // cool, `user` is a User, it must have the `name` property!
  user.name.length; // fails
}
Enter fullscreen mode Exit fullscreen mode

whereas in TypeScript, any operation changing the shape of an object outside of its type is prevented

type User = { name: string }
const user = { name: 'john' }
delete user.name; // Error: The operand of a 'delete' operator must be optional.(TS2790)
Enter fullscreen mode Exit fullscreen mode
Collapse
cherif_b profile image
Cherif BOUCHELAGHEM Author

I agree, however there's other ways to prevent this like freezing or using Proxies.

Collapse
aminnairi profile image
Amin • Edited
type User = { name: string }
const user = { name: 'john' }

Object.defineProperty(user, "name", {
  value: undefined
});

alert(user.name.length); // Cannot read property 'length' of undefined (in JavaScript after transpilation)
Enter fullscreen mode Exit fullscreen mode

This compiles just fine in TypeScript and even gives an error in the playground when run.

Collapse
ninofiliu profile image
Nino Filiu

Sure, but come on, that's just deliberately trying to deceive TypeScript at this point ^^