我正在为 a library 快速组装一个 .d.ts
, 但遇到了以下问题:
class Issuer {
constructor(metadata) {
// ...
const self = this;
Object.defineProperty(this, 'Client', {
value: class Client extends BaseClient {
static get issuer() {
return self;
}
get issuer() {
return this.constructor.issuer;
}
},
});
}
// ...
}
这是从面向用户的 API 本身使用的(googleIssuer
是 Issuer 的一个实例)。
const client = new googleIssuer.Client({
// ...
})
我尝试使用同名命名空间扩展 Issuer 类定义,但这并不像我希望的那样。
在我的定义中,最简单的表示方法是什么?
最佳答案
使用类和命名空间合并,你得到一个静态类的等价物(一个可以使用类访问的类,而不是类的实例):
declare class Issuer {
}
declare namespace Issuer {
class Client{}
}
declare class GoogleIssuer extends Issuer {
}
let d = new GoogleIssuer.Client() // Ok
let googleIssuer = new GoogleIssuer();
let c = new googleIssuer.Client() // error
您需要的是一个绑定(bind)到类实例的类定义。为此,您可以将该类声明为 Issuer
类的一个字段:
// Declare the structure of client separately
declare class Client {
}
declare class Issuer {
Client: typeof Client; // Declare a field that is of the class type
}
declare class GoogleIssuer extends Issuer {
}
let googleIssuer = new GoogleIssuer();
let c = new googleIssuer.Client() // ok
关于javascript - 类的 typescript 定义作为对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49250229/