Function parameter to use the interface function signature

I have a function signature in an interface that I would like to use as a signature for a callback parameter in some class.

export interface IGrid {
    gridFormat(gridCell: GridCell, grid: Grid): boolean
}

      

I would like to do something like this:

validateFormat(validator: IGrid.gridFormat) {
    // ...
}

      

Is it possible?

+3


source to share


2 answers


Is it possible?

Yes, as shown below:



export interface IGrid {
    gridFormat(gridCell: GridCell, grid: Grid): boolean
}

function validateFormat(validator: IGrid['gridFormat']) { // MAGIC 🌹
    // ...
}

      

+4


source


You can try something like the following:

export interface IGrid {
  gridFormat(gridCell: GridCell, grid: Grid): boolean
}

declare let igrid: IGrid;

export class Test {
  validateFormat(validator: typeof igrid.gridFormat) {
    // ...
  }
}

      

Alternatively, you can also declare a type for the method as shown below

declare type gridFormatMethodType = typeof igrid.gridFormat

      



to avoid the cumbersome method signature for validateFormat

validateFormat(validator: gridFormatMethodType){ ... }

      

Hope it helps.

+1


source







All Articles