I try to learn decorators in typescript and follow the instruction of the course till in function controller it's a function try to loop through class Plane property to get Metadata out of it from secret but it can't loop through because the target.prototype is always return empty object {}
import 'reflect-metadata'
@controller
class Plane {
color: string = 'red'
constructor() {
this.color = 'red'
}
@get('/login')
login(): void {
console.log('Login Route Open')
}
@markFunction('XAF123FF2Sx1')
fly(): void {
console.log('Flying!!')
}
}
function markFunction(secretInfo: string) {
return function (target: Plane, key: string) {
Reflect.defineMetadata('secret', secretInfo, target, key)
}
}
function controller(target: typeof Plane) {
target.prototype.fly = function (): string {
return 'Hello Bytefer'
}
// This Line !!!
console.log(target.prototype)
for (let key in target.prototype) {
const path = Reflect.getMetadata('secret', target.prototype, key)
console.log(path)
}
}
function get(path: string) {
return function (target: Plane, key: string) {
Reflect.defineMetadata('path', path, target, key)
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"experimentalDecorators": true,
"useDefineForClassFields": false,
"emitDecoratorMetadata": true,
/* Modules */
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
package.json
{
"name": "features",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"reflect-metadata": "^0.1.13"
}
}
nodejs v18.16.1 typescript v5.1.6
I want to know how can I get key in target.prototype from decorators in class