ts 类装饰器的不足

原文链接: ts 类装饰器的不足

上一篇: ts 装饰器

下一篇: js worker 快速传递数组

https://www.tslang.cn/play/index.html

使用函数调用是可以增强方法的

up-fc960d1e732c845a7cce420e7752c30459d.png

interface IRun {
  age: number;
  run(): void;
}

function testDecorator() {
  return function<T extends new (...args: any[]) => any>(constructor: T) {
    console.log('1');
    return class extends constructor implements IRun {
      name = 'lee';
      age = 13;
      getName() {
        return this.name;
      }
      run() {}
    };
  };
}

const Test = testDecorator()(
  class {
    name: string;
    constructor(name: string) {
      this.name = name;
    }
  }
);

const test = new Test('d');
console.log(test.getName());

如果用装饰器的写法, 虽然执行时有, 但是提示确实没有的, 会报错....

up-e0804db632d5db88c3886c582a300d797e4.png

up-c210f4787ed78c4dd2b8289845b82a9071f.png

可以用下的方法重新创建类,或者强转any

up-45baf8b1b9a8ebd94d5e995626fdb0a300d.png

up-f4c90bf35ff959a27e4e17f3c4a5eee7975.png

up-a5f794637ce301f133e3f5248094d1ac427.png

up-79c5cb27ad0905148f823fe5300c43cd7b2.png

interface IRun {
    age: number
    run(): void
}

function testDecorator() {
    return function <T extends new (...args: any[]) => any>(constructor: T) {
        console.log("1")
        return class extends constructor implements IRun {
            name = "lee"
            age = 13
            getName() {
                return this.name
            }
            run() { }
        }
    }
}

@testDecorator()
class Test {
    name: string
    constructor(name: string) {
        this.name = name
    }
}

const test = new Test("d")
console.log(test.getName())


const Test2 = testDecorator()(
  class {
    name: string;
    constructor(name: string) {
      this.name = name;
    }
  }
);
const test2 = new Test2("d")
console.log(test2.getName())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值