Open lockHrt opened 2 years ago
the difference is probably because of public instance class fields
target: es2021
and below would output:
class User {}
target: es2022
and above would output:
class User {
id;
firstName;
lastName;
}
and this means that when you would do new User()
, then the following would happen:
target: es2021
(and below): User {}
target: es2022
(and above): User { id: undefined, firstName: undefined, lastName: undefined }
this means that js works by adding all defined values, even if not set by the constructor Also see MDN: Classes: Field declarations Quote:
By declaring fields up-front, class definitions become more self-documenting, and the fields are always present.
PS: the documentation was made before es2022
was available, and it does not seem like the documentation (or package itself) will be updated any time soon)
Be careful, if you use target: 'es2022'
and the exposeUnsetFields: false
option, unset fields will be exposed. Affected lines of code: https://github.com/typestack/class-transformer/blob/master/src/TransformOperationExecutor.ts#L160
I can confirm the behavior is different with newer target versions:
class Cat {
name: string;
age?: number;
}
const plainObj: any = {
name: 'Meowth',
};
const cat = plainToInstance<Cat, any>(Cat, plainObj);
Cat { name: 'Meowth' }
Cat { name: 'Meowth' }
Cat { name: 'Meowth', age: undefined }
Cat { name: 'Meowth', age: undefined }
@lockHrt In the title of this issue you probably meant "ES2022" instead of "ES2021"
@lockHrt In the title of this issue you probably meant "ES2022" instead of "ES2021"
You're right. Corrected the title.
Same problem here using ES2022
Description
If tsconfig.json has
"target": "ES2022"
or"target": "ESNext"
, the results are different from what have been mentioned in the documentation.Minimal code-snippet showcasing the problem
This very simple example is taken from the documentation itself.
Expected console log
When tsconfig
target
is 2021 or lowerActual console log
When tsconfig
target
is 2022 or higherOther files
tsconfig.json
package.json
node version is 16.14.2