Looking to implement a feature in Java/TypeScript where I can automatically add properties without writing them into the constructor. As a beginner, my attempt might not be perfect. Here's what I have so far...
The idea is to achieve something like this:
class A {
@uuid
'property': string;
'another': string;
}
function uuid(target: any, key: string): void {
Reflect.defineMetadata('isUuid', true, target, key);
}
With A
's constructor new () => Object
, I should be able to retrieve all the properties and check if they are UUIDs like this:
Object.keys(A).forEach(key => {
console.log(`[${key}].isUuid? ${Reflect.getMetadata('isUuid', A, key) === true}`);
});
This should ideally output:
[property].isUuid? true
[another].isUuid? false
If I modify class A
as follows:
class A {
constructor() {
this.property = undefined;
this.another = undefined;
}
@uuid
'property': string;
'another': string;
}
I can make it work, but I need to instantiate A
to access the keys and metadata.