Class-transformer: question: support for setting private readonly properties

Created on 5 May 2019  路  5Comments  路  Source: typestack/class-transformer

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?

needs docs question

Most helpful comment

Is this an acceptable solution?

export class ImmutableFoo {
  @Expose({ name: 'bar', toClassOnly: true })
  private readonly _bar: string;

  get bar(): string {
    return this._bar;
  }
}

All 5 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gregsolo-intent picture gregsolo-intent  路  5Comments

NoNameProvided picture NoNameProvided  路  5Comments

prbaron picture prbaron  路  3Comments

ceopaludetto picture ceopaludetto  路  3Comments

weeco picture weeco  路  5Comments