A day ago I asked my developers friends:
How to know a JavaScript object literal type?
Most of the answers of the answers suggested to use inst...
For further actions, you may consider blocking this person and/or reporting abuse
Nice, I didn't know about this!
But I wouldn't trust this trick for type-safety checking
whereas in TypeScript, any operation changing the shape of an object outside of its type is prevented
It's important not to forget that, at the end of the day, TypeScript isn't anything more than code sugar, pre-compilation. Post-compilation (and subsequent runtime), it's all regular ole' JavaScript. Nothing more. Nothing less. Enforcing "Type" safety in any kind of "strict" manner, will always, always, always only go so far. ECMAScript Primitives are the only datums which, natively, guarantee preserving "Type"(Undefined, Null, String, Boolean, Number, and Symbol). All remaining ECMAScript types/values fall under "Object Type" classifications/sub-classes. Why is any of this important? Objects, (be it a "POJO", function, constructor, exotic, emoji, whatever), by their very nature in JavaScript land are not ever going to be "secure", ESPECIALLY in terms of structural exposition/composition (i.e. "interface" or "shape"). However, we CAN secure "Object Type" checks and guards that remain true at runtime by placing the intended "Type" enforcements around the instance itself.
Totally agreed! Thank you!
This compiles just fine in TypeScript and even gives an error in the playground when run.
Sure, but come on, that's just deliberately trying to deceive TypeScript at this point ^^
I agree, however there's other ways to prevent this like freezing or using Proxies.
Very interesting. How I wish this was a built-in feature.
It is built-in you just need to override the Symbol.
No I mean built-in as in you don't have to code anything else, just do a
user.toStringTag()
and it'll return[object user]
.interesting, ready i like the way how did you explain it, thnaks
Very useful. Thanks!
thank you 🙏🏻