【问题标题】:Enfore required fields in TypeScript (and work with var-arg constructor)?在 TypeScript 中输入必填字段(并使用 var-arg 构造函数)?
【发布时间】:2015-01-23 17:56:41
【问题描述】:

由于 TypeScript 1.3 还没有抽象字段,因此要求设置字段的方法之一是将其作为构造函数参数。

然而,由于这个版本也没有展开操作符,如果子节点也必须将 var-arg 传递给父节点,这将不能很好地工作。例如:

class Parent {
    constructor (required1, required2, ...rest) { //...
}

class Child extends Parent {
    constructor (...args) {
       super(val1, val2, ???);
}

在普通的 JavaScript 中,这种模式通常是通过切片并将arguments 应用于超级构造函数来完成的。但是,这种解决方法不起作用,因为只能调用 super 而不能打开 apply()

我错过了什么吗?否则,是否有任何替代方法可以实现相同的目标?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    遗憾的是,您需要欺骗 TypeScript 编译器

    class Parent {
        constructor (required1, required2, ...rest) { //...
            if(required1 == void 0) return;
        }
    }
    
    class Child extends Parent {
        constructor (...args) {
           super(undefined,undefined); // make the compiler happy
           Parent.apply(this,[val1,val2].concat(args)) // the actual call  
        }
    }
    

    我已经记录了一个获得 TS 团队意见的建议:https://github.com/Microsoft/TypeScript/issues/1790

    【讨论】:

      猜你喜欢
      • 2011-03-28
      • 2022-04-22
      • 2014-05-14
      • 2012-05-08
      • 2017-07-20
      • 2021-07-18
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多