在声明文件中描述mixins

问题描述 投票:1回答:1

假设您要为其创建打字的现有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,以便传达某些成员是由/通过其构造函数创建的?

javascript typescript typescript-typings
1个回答
0
投票

你真的需要这种区别吗?你的构造函数总是创建那些成员,所以如果你有一个类型为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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.