Skip to content

fix: plainToInstance will throw an error when exposing a getter in the parent class #1257

Open
@CodyTseng

Description

@CodyTseng

Description

Minimal code-snippet showcasing the problem

import { Expose, plainToInstance } from 'class-transformer'

class Person {
  firstName: string;
  lastName: string;

  @Expose()
  get name() {
    return this.firstName + ' ' + this.lastName;
  }

  say() {
    console.log(`My name is ${this.name}`);
  }
}

class Programmer extends Person {
  language: string;

  say() {
    console.log(`My name is ${this.name}. I'm a ${this.language} programmer.`);
  }
}

const programmer = plainToInstance(Programmer, {
  firstName: 'Umed',
  lastName: 'Khudoiberdiev',
  language: 'JavaScript',
});

programmer.say();

console.log(instanceToPlain(programmer));

Expected behavior

Output:

My name is Umed Khudoiberdiev. I'm a JavaScript programmer.
{
  firstName: 'Umed',
  lastName: 'Khudoiberdiev',
  language: 'JavaScript',
  name: 'Umed Khudoiberdiev'
}

Actual behavior

/****/node_modules/class-transformer/cjs/TransformOperationExecutor.js:309
                            newValue[newValueKey] = finalValue;
                                                  ^

TypeError: Cannot set property name of #<Person> which has only a getter
    at TransformOperationExecutor.transform (/****/node_modules/class-transformer/cjs/TransformOperationExecutor.js:309:51)
    at ClassTransformer.plainToInstance (/****/node_modules/class-transformer/cjs/ClassTransformer.js:27:25)
    at plainToInstance (/****/node_modules/class-transformer/cjs/index.js:38:29)
    at Object.<anonymous> (/****/index.js:31:60)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: fixedIssues with merged PRs, but not released yettype: 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