If i am using a class like:
export class ImmutableFoo {
get bar(): string {
return this._bar;
}
private readonly _bar: string;
}
with
plainToClass(ImmutableFOO, {bar: "qwert"});
then bar is undefined.
Is ther any way to use the libary with private readonly properties?
Hi @martin-hess-arithnea!
Currently, you cannot, the library checks if the property is writable and skips it if not.
However, I think this is a valid use-case so I think this should work:
import 'reflect-metadata';
import { plainToClass, Transform } from 'class-transformer';
export class ImmutableFoo {
private readonly _bar: string;
@Transform((value, obj) => obj._bar = value, { toClassOnly: true })
get bar(): string {
return this._bar;
}
}
const instance = plainToClass(ImmutableFoo, { bar: 'qwert'});
console.assert(instance.bar === 'qwert', <any>{ expected: 'qwert', actual: instance.bar});
Doesn't seem to work either. So i stick to readonly props instead of private for now :-/
It would be nice to have a ClassTransformOptions in a future release like
plainToClass(ImmutableFOO, {bar: "qwert"}, { privatePropertyPrefix: "_"});
Is this an acceptable solution?
export class ImmutableFoo {
@Expose({ name: 'bar', toClassOnly: true })
private readonly _bar: string;
get bar(): string {
return this._bar;
}
}
Hi @Petr0vi4,
Your example resolved to me, although, I had to add ! because of error:
Property '_bar' has no initializer and is not definitely assigned in the constructor
Thanks!
Closing this as solved. @Petr0vi4's answer is the right solution here.
I am adding a need docs flag as this should be documented as an example for working with getters/setters.
Most helpful comment
Is this an acceptable solution?