账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    如何为装饰器声明类型
    48
    0
    以方法装饰器为例.被装饰后的方法执行后会改变返回值.如何将这样的变更,使ts能够察觉到?const ranger = (min: number, max: number) => Math.floor(Math.random()*(max-min+1)+min);// 错误时,为方法返回值补充error字段function Catch(target: any, key: string, descriptor: PropertyDescriptor) { const fn = descriptor.value descriptor.value = async function (...args: any[]) { try { return await fn.apply(this, args) } catch (error) { return { code: 1, error: [error.message || '异常'] } } } return descriptor}// 被装饰的方法,可以安全得调用api.class Test { @Catch async test() { const value = ranger(0, 100) if (value > 50) { throw new Error('something went wrong') } return {code: 0, data: {value}} }}const t = new Test()t.test() .then(res => { // 然而这里无法知道res有error这个字段 })ts虽然支持了装饰器,然而并没有正确地自动推断出被装饰后的方法返回值
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 采风西南 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部