How to reuse function signature definition in TypeScript

Viewed 5967

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?

2 Answers
interface Callback {
    (n:number):number;
}

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

    public readonly defaultFn: Callback = (a: number): number => {
        return a + 1;
    }

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

You can also simply do this

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

Or combine with an interface

interface Callback {
    (n:number):number;
}

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

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

Related