任務是實作類裝飾器以添加“identify”類方法,該方法回傳一個類名以及裝飾器中傳遞的資訊。
例子:
@identifier('example')
class Test {}
const test = new Test();
console.log(test['identify']()); // Test-example
單元測驗:
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');
})
我試圖用這個裝飾器做點什么,但我現在只有控制臺記錄括號中傳遞的字串,我不知道如何列印使用裝飾器的類名。請幫忙。:
我的功能:
function identifier(passedInformation:string):string {
console.log('-' passedInformation)
}
編輯:我幾乎完成了這個功能:
function identifier(...args: any): ClassDecorator {
return function <TFunction extends Function>(
target: TFunction
): TFunction | void {
return target.name '-' args)
}
}
如果我更改return target.name '-' args控制臺日志,它會給出登錄控制臺的單元測驗中預期的結果,但問題是我得到: 型別“字串”不可分配給型別“無效 | TFunction'
這在 junit.xml 中:
<failure message="" type="TypeError"><![CDATA[TypeError:
at DecorateConstructor (node_modules\reflect-metadata\Reflect.js:544:31)
at Object.decorate (node_modules\reflect-metadata\Reflect.js:130:24)
at __decorate (test\index.ts:4:92)
但是如果我將回傳更改為控制臺日志,我會在 junit.xml 中得到這個:
<failure message="test.identify is not a function" type="TypeError"><![CDATA[TypeError: test.identify is not a function
at Context.<anonymous> (test\index.ts:99:44)
怎么了?我怎樣才能回傳我的結果并完成這項任務?
編輯 2:
使用下面的@Vallarasu SambathKumar 解決方案,我在代碼編輯器中沒有收到任何錯誤,但在 junit.xml 中我收到下一個錯誤,它無法通過單元測驗..:
<failure message="" type="TypeError"><![CDATA[TypeError:
at DecorateConstructor (node_modules\reflect-metadata\Reflect.js:544:31)
at Object.decorate (node_modules\reflect-metadata\Reflect.js:130:24)
at __decorate (test\index.ts:4:92)
at C:\Users\artio\Desktop\6 Decorators\decorators\test\index.ts:81:20
at Context.<anonymous> (test\index.ts:85:10)
at processImmediate (internal/timers.js:439:21)]]></failure>
如何解決這個問題,什么問題?
uj5u.com熱心網友回復:
您也可以將實體作為引數傳遞并訪問它的型別
function identifier(passedInformation:string) {
return function (target) {
console.log(target.constructor.name '-' passedInformation);
}
}
并像使用它一樣
test['identify'](test)
即興從 -在運行時獲取物件的類名
uj5u.com熱心網友回復:
使用@Vallarasu SambathKumar 解決方案和更多檔案,我想出了這個功能:
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;
};
}
我按照需要的任務執行了識別方法,然后回傳它,在單元測驗和運行時沒有錯誤,完美。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411851.html
標籤:
