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
I found the solution using class-transformer
, it requires an extra trick.
@Expose()
decorator with the option toPlainOnly
property set to true
class A {
@Expose({ name: 'desc', toPlainOnly: true })
description: string
}
const x = plainToInstance(A, { description: "xxx xxx xxx" })
const y = instanceToPlain(x, {})
console.log(y) // { desc: "xxx xxx xxx" } ✅ works!