Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse function signature definition in TypeScript

Tags:

typescript

I've got the following code:

class A {
  constructor(public n: number) {}  

  defaultFn(a: number): number {
    return a + 1;
  }

  doStuff(callback?): number {
    return callback ? callback(this.n) : this.defaultFn(this.n);
  }
}

How can I tell TypeScript that the optional callback function passed to doStuff method should have the same signature as defaultFn method?

like image 807
szimek Avatar asked Nov 11 '17 18:11

szimek


People also ask

How do you pass a function as a parameter in TypeScript?

Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.

What does ?: Mean in TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

How do I add a return type in TypeScript?

To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.


1 Answers

One more option is to "query" type of defaultFn. In this case you won't need to maintain the type of callback manually:

class A {
    constructor(public n: number) {}  

    defaultFn(a: number): number {
        return a + 1;
    }

    doStuff(callback?: A['defaultFn']): number {
        return callback ? callback(this.n) : this.defaultFn(this.n);
    }
}

The result of A['deafultFn'] is (a: number) => number

like image 123
Aleksey L. Avatar answered Oct 14 '22 08:10

Aleksey L.