1. 程式人生 > 實用技巧 >TypeScript 裝飾器例項

TypeScript 裝飾器例項

const userInfo: any = undefined;

class Test{
  getName() {
    return userInfo.name;
  }
  getAge() {
    return userInfo.age;
  }
}

const test = new Test();
test.getName();
這個例子執行的時候會報錯,因為 name,age 不存在,userInfo 是 undefined,進行以下方式處理
const userInfo: any = undefined;

class Test{
  getName() {
    
try { return userInfo.name; } catch (e) { console.log('userinfo.name 不存在') } } getAge() { try { return userInfo.info; } catch (e) { console.log('userinfo.info 不存在') } } } const test = new Test(); test.getName();
假設這裡有很多getName,getAge 的方法,很多的 try...catch 程式碼會變得很長,我們用裝飾器解決 try...catch 反覆編寫的問題
const userInfo: any = undefined;

function catchError(target: any, key: string, descriptor: PropertyDescriptor) { const fn = descriptor.value; descriptor.value = function () { try { fn(); } catch (e) { console.log('userinfo 存在問題') } } } class Test{ @catchError getName() { return userInfo.name; } @catchError getAge() {
return userInfo.info; } } const test = new Test(); test.getAge();