#Very confused about typescript classes

8 messages · Page 1 of 1 (latest)

keen ridge
#

Note: I am coming into this question (and typescript in general) from the prespective of NestJS.
This may not be the right place to ask this, but I've noticed how you must specify Expose() decorator when transforming with class-transformer with the option excludeExtranousValues set to true...
I read some more about this and what I understood is that without the decorator, when typescript is converted to javascript it loses the properties and so can't know which properties belong to the class hence why you need the decorator.

The thing is.. This is not correct... When creating a random class with typescript and transpiling it into javascript I can clearly see all the properties still intact in the javascript class, and if I run a short js script utilizing this class, for instance:

class Who {
  prop1;
  prop2;
}

const obj = new Who();
console.log(Object.keys(obj));

Javascript clearly knows which properties belong to the class...
So the question remains - why are decorators so important to know which properties belong to the class if it seems like we can know it without them as well..?

#

Very confused about typescript classes

topaz lynx
#

that is the flag that hides all properties by default

keen ridge
#

Welp, I figured it out and I don't like the answer lol
In ES2022 public class fields feature was introduced to javascript, this made it possible for a class to hold properties.
So basically, the whole decorator shenanigans are no longer needed for this purpose.
Why are they still here?
Because class-transformer and class-validator haven't gotten an update in over 2 years ;-;

keen ridge
# topaz lynx that is the flag that hides all properties by default

You'd expect it to be possible to tell it to only allow properties of the class, but they claimed in some issues I saw on github that it is impossible because javascript classes aren't aware of their properties...
Hence why you must have at least one decorator so that it can emit metadata and make it possible to know which properties the class has.

But now... Classes can have properties in pure javascript so... 😛

topaz lynx
keen ridge
#

Right now yes, but there's no way to tell it to just ignore properties that don't belong to the class without this option