mitchkman
mitchkman

Reputation: 6680

Retaining original functioon signature when overriding class function in TypeScript

I have the following example code:

// I don't have control over class A
class A {
    func(a: string, b: int) {
        ...
    }
}

...

class B extends A {
    func(a, b) {
        return super.func(a, transform(b))
    }
}

...
function transform(x) {
    return ...;
}

I want B.func(a, b) to retain the original function type. Right now, a and b are implicitly any. How can I have a and b correctly typed (string and int), without explicitly re-assigning the types?

In principle, I want to achieve something like (pseudocode):

class B extends A {
    func(a, b) as typeof super.func {
        return super.func(a, transform(b))
    }
}

Upvotes: 0

Views: 24

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42228

You can do this by assigning a type to the function itself based on the A function type. We use an indexed access to get the type of A.func as A['func'].

It's easy to write with an arrow function because you can insert the function type after the function name and before the =.

class B extends A {
    func: A['func'] = (a, b) => {
        return super.func(a, transform(b))
    }
}

Typescript Playground Link

Upvotes: 1

Related Questions