billc.cn
billc.cn

Reputation: 7317

Enfore required fields in TypeScript (and work with var-arg constructor)?

Since TypeScript 1.3 doesn't yet have abstract fields, one of the ways to require a field to be set is to put it as a constructor argument.

However, since this version also don't have spread operators, this does not work very well if the child also has to pass a var-arg to the parent. For example:

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

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

In plain-old JavaScript, this pattern is usually done through slicing and applying arguments to the super constructor. However, such workaround does not work as super can only be called and not apply() on.

Have I missed something? Otherwise, is there any alternatives to achieve the same thing?

Upvotes: 1

Views: 100

Answers (1)

basarat
basarat

Reputation: 276239

Sadly you need to trick the TypeScript compiler

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  
    }
}

I've logged a suggestion to get the TS team input : https://github.com/Microsoft/TypeScript/issues/1790

Upvotes: 3

Related Questions