Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spread syntax in typescript

I'm trying to extend a class in an Angular project and I want to pass arguments to the parent class using the rest/spread syntax of ES2015 like the answer to this question

constructor(...args) {
    super(...args);
}

but I get an error Supplied parameters do not match any signature of call target and my app won't compile.

I made a contrived example using the typescript playground. Does anyone know how to get this to work without having to explicitly write the arguments of the parent class methods?

UPDATE: As pointed out by Teddy Sterne I actually don't need to use this for the constructor because it has the same arguments. I actually want to use this for a method that returns an observable. I want to catch errors by overriding the method and returning super.parentMethod(...args).catch(/* deal with error */)

like image 333
Devin Crossman Avatar asked Oct 04 '26 09:10

Devin Crossman


2 Answers

Another workaround would be to use the built-in ConstructorParameters Type Helper.

class A {
    constructor (foo: number, bar: string) {}
}


class B extends A {
    constructor (...args: ConstructorParameters<typeof A>) {
        super(...args);
    }
}
like image 87
tenbits Avatar answered Oct 05 '26 21:10

tenbits


This question was asked and answered in this issue: https://github.com/Microsoft/TypeScript/issues/11679

You are correct assuming it's because of type checking. Lets assume the parent constructor expects a fixed number of parameters. At the point super(...args) is declared, the compiler doesn't know the actual number of passed parameters. Therefore it flags it as unsafe.

like image 32
tony Avatar answered Oct 05 '26 21:10

tony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!