>假设一个现有的Javascript框架,你想要为其创建类型。Javascript代码使用Node.js模块,原型继承和mixins:
// File: src/lib/a.js
function A() {
this.isA = true;
this.type = 'a';
}
module.exports = A;
// File: src/lib/b.js
var A = require('./a');
var plugin = require('./plugin');
function B() {
A.call(this);
this.isB = true;
this.type = 'b';
plugin(this);
}
B.prototype = object.create(A.prototype);
B.prototype.constructor = B;
module.exports = B;
// File: src/lib/plugin.js
function plugin(obj) {
obj.doSomethingFancy = function() {
// ...
}
}
module.exports = plugin;
您将如何在声明文件中描述B
,以便它传达某些成员是由其构造函数创建的/通过其构造函数创建的?
你真的需要这种区别吗?构造函数始终创建这些成员,因此,如果您有类型 B
的对象 - 则可以确定这些属性将在那里。
如果你想发出信号,一个成员可能不存在 - 用?
后缀它的名字,就像我在下面的例子中为doSomethinFancy
所做的那样。
class A {
public isA: boolean;
public type: string;
constructor() {
this.isA = true;
this.type = 'a';
}
}
function plugin(obj: any): any {
obj.doSomethingFancy = function() {
// ...
}
}
class B extends A {
public isB: boolean;
// same could be used for optional function arguments
public doSomethingFancy?: () => {};
constructor() {
super();
this.isB = true;
this.type = 'b';
plugin(this);
}
}