裝飾器基礎(Typescript)

import "reflect-metadata";

// 基礎
@Reflect.metadata("class", "value_test")
class Test {

    @Reflect.metadata("field", "value_name")
    name = "dottie";

    @Reflect.metadata('method', "value_hi")
    hi(): string {
        return 'hi, today!'
    }
}

console.log(Reflect.getMetadata('class', Test)); // value_test
console.log(Reflect.getMetadata('field', Test.prototype, 'name')); // value_name
console.log(Reflect.getMetadata('method', Test.prototype, "hi")); //  value_hi

// 獲取類型信息,返回值,參數等信息
function PropDeco(): PropertyDecorator {
    return (target: any, key: any) => {
        console.log(target); // SomeClass {}
        const type = Reflect.getMetadata("design:type", target, key);
        console.log(type.name); // String
    }
}

class SomeClass {
    @PropDeco()
    public name!: string;
}

// 自定義 metadatakey
function Component(value?: string): ClassDecorator {
    return (target: any) => {
        Reflect.defineMetadata("component", value, target);
    }
}

function Resource(value?: string): PropertyDecorator {
    return (target: any, key: any) => {
        Reflect.defineMetadata("field", value, target, key);
    }
}

function Method(): MethodDecorator {
    return (target: any, key: any, descriptor: any) => {
        Reflect.defineMetadata('method', descriptor.value, target, key);
    }
}

@Component("app")
class TestClass {
    @Resource("這是姓名")
    public name!: string;

    @Method()
    public hi():String {
        return "hi!";
    }
}

const cValue = Reflect.getMetadata('component', TestClass);
console.log(cValue); // app
const fValue = Reflect.getMetadata('field', TestClass.prototype, 'name');
console.log(fValue); // 這是姓名
const mValue = Reflect.getMetadata('method', TestClass.prototype, "hi");
console.log(mValue); // [Function]
console.log(mValue.call(null)) // hi!
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容