I have a task to Implement the class decorator to add the “identify“ class method which returns a class name with the information passed in the decorator.
For example:
typescript
@identifier('example')
class Test {}
const test = new Test();
console.log(test['identify']()); // Test-example
The problem is that I found out documentation where is written that I can get class name only doing const x = new Class Y and use .name function, but in my case, I don't know how the class or variable where the instance will be stored. Maybe getting this information from test units could get this done but I don't know the perfect approach cuz I'm new in typescript.
This is my try of doing the function :
const identifier = (text : string) => {
console.log(test.constructor.name)
return test.constructor.name
}
Yes, it's barely anything, but I don't know from where to start.
Unit tests :
describe('identifier', () => {
it('should return Test-example from identify', () => {
@identifier('example')
class Test {}
const test = new Test();
assert.strictEqual(test['identify'](), 'Test-example');
});
it('should return ClassA-prototype from identify', () => {
@identifier('prototype')
class ClassA {}
const test = new ClassA();
assert.strictEqual(test['identify'](), 'ClassA-prototype');
})
});
Could you guys please help me? Thank you!
I came up with this function that solves my issue :
function identifier(...args: any): ClassDecorator {
return function <TFunction extends Function>(
target: TFunction
): TFunction | any {
var identify = target.prototype.identify;
Object.defineProperty(target.prototype, 'identify', {
value: function() {
return target.name + "-" + args;
}
});
return identify;
};
}
It creates the identify method for the class,pass to the method the class name and the string from parantheses and then return it.