Skip to content

fix: Expose with name doesn't work when there is a getter/setter even if the getter is excluded #1261

Open
@lintyao

Description

@lintyao

Description

I have a class looks like:

class Test {
    _someValue: number = 0

    get someValue(): number {
      return this._someValue
    }
    
    set someValue(value: number) {
      // some setter logic
      this._someValue = value
    }
 }

I would like to set the value directly to the private field _someValue instead of going through the setter when invoking plainToInstance(). Therefore I expose the private field with name someValue and @Exclude() the getter/setter property. However, plainToInstance in this case ignores this field completely.

Minimal code-snippet showcasing the problem

class Test {
    @Expose({ name: 'someValue' })
    _someValue: number = 0

    get someValue(): number {
      return this._someValue
    }
    @Exclude()
    set someValue(value: number) {
      this._someValue = value
    }
 }
const plain = {
  someValue: 1000
}

Expected behavior

plainToInstance(Test, plain)
// { _someValue: 1000 }

Actual behavior

plainToInstance(Test, plain)
// { _someValue: 0 }

The behavior is different when there is no getter/setter with the same name, and plainToInstance works as expected in this case.

// This works as expected
class Test {
    @Expose({ name: 'someValue' })
    _someValue: number = 0
 }
const plain = {
  someValue: 1000
}
plainToInstance(Test, plain)
// { _someValue: 1000 }

I wonder if there is anything I can do to configure plainToInstance to set values directly to the private field?
Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: needs triageIssues which needs to be reproduced to be verified report.type: fixIssues describing a broken feature.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions