Search code examples
typescriptclass-transformer

How to rename the instance keys using decorators?


I have this class:

class A {
  description: string
}

I want when creating an instance from this class to normally call description in order to set it. But when accessing the class instance, I want it to become a.desc.

Normally, you'd do something like this:

class A {
  desc: string
  constructor(description: string) {
    this.desc = description
  }
}
const instance = new A("xxx xxx xxx")
console.log(instance) // { desc: "xxx xxx xxx" }
console.log(instance) // "xxx xxx xxx"

I was thinking, can I do something like this?

class A {
  @RenameKey("desc")
  description: string
}

I found the @Expose() decorator, but it changes the input and output property name, I want the property name of the input to be description normally, but the output should be desc.

Question: Is it possible to rename the class instance keys using decorators? I know can do this:

const a = new A("xxx xxx xxx")
a.desc = a.description
delete a.description

But I want to achieve this using decorators


Solution

  • I found the solution using class-transformer, it requires an extra trick.

    1. Define your class and using the @Expose() decorator with the option toPlainOnly property set to true
    class A {
     @Expose({ name: 'desc', toPlainOnly: true })
      description: string
    }
    
    1. Create an instance from the class:
    const x = plainToInstance(A, { description: "xxx xxx xxx" })
    
    1. return the instance back to plain object:
    const y = instanceToPlain(x, {})
    console.log(y) // { desc: "xxx xxx xxx" } ✅ works!