I have a scenario where I have a class defined as follows:
class A {
description: string
}
My requirement is that when creating an instance of this class, I want to set the description
attribute. However, when accessing the instance of the class, I would like to use a.desc
.
The usual approach for this would be something like:
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 wondering if there is a way to achieve this using decorators like below:
class A {
@RenameKey("desc")
description: string
}
I came across the @Expose()
decorator, but it changes both the input and output property names. What I am looking for is to keep the input property name as description
while having the output as desc
.
So my question is: Can we rename the keys of a class instance using decorators?
const a = new A("xxx xxx xxx")
a.desc = a.description
delete a.description
Although the above code snippet achieves what I want, I am interested in exploring decorator-based solutions.