相关疑难解决方法(0)

通过 TypeScript 中的装饰器向类添加属性

在 TypeScript 的装饰器参考页面上,有一段代码被截断,说明如何使用类装饰器覆盖构造函数:

function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
    return class extends constructor {
        newProperty = "new property";
        hello = "override";
    }
}

@classDecorator
class Greeter {
    property = "property";
    hello: string;
    constructor(m: string) {
        this.hello = m;
    }
}

console.log(new Greeter("world"));
Run Code Online (Sandbox Code Playgroud)

并在日志中:

class_1 {
  property: 'property',
  hello: 'override',
  newProperty: 'new property' }
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好。但是尝试newProperty通过点符号访问失败:

类型“Greeter”.ts(2339) 上不存在属性“newProperty”

错误并且未在 VS Code 的提示中列出。可以通过括号表示法访问它,但 TS 警告说

元素隐式具有 'any' 类型,因为类型 'Greeter' 没有索引签名。 ts(7017)

我错过了什么吗?如何以类型安全的方式通过装饰器实现添加新属性?我想像普通的类成员一样拥有普通的编译器支持。

decorator mixins typescript

13
推荐指数
2
解决办法
7478
查看次数

打字稿声明:合并一个类和一个接口

我有两个模型Model,其子类ClientModel为环境模块。现在,我想ClientModel从所谓的接口声明一组属性Client。我该怎么做?我可以想象这样的事情:

interface Client {
    name: string;
    email: string;
}

declare class ClientModel extends Model implements Client {
    // with name and email here without redeclare them
}
Run Code Online (Sandbox Code Playgroud)

inheritance declaration ambient typescript

3
推荐指数
1
解决办法
2513
查看次数