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();