Home > Blockchain >  How to indicate function parameter function input type
How to indicate function parameter function input type

Time:07-05

I am new to typescript. I have a function that takes a function as an input parameter. This input parameter function has number input value.

preloadResources(informLoadPct: Function)
{
  let pct = 100;
  informLoadPct(pct);

}

I call this function like this

preloadResources((loadedPercentage: number) => {
  console.log(loadedPercentage);
});

as you can see the function parameter is a function that has number input type. Is there a way to define that also?

instead of "informLoadPct: Function" can we provide more information about this function?

CodePudding user response:

You sure can. My prefered way is as follows:

type NumberLogger = (n: number) => void;

function preloadResources(informLoadPct: NumberLogger )
{
  let pct = 100;
  informLoadPct(pct);

}

If you ever need to pass this inside an object, you can do the same thing.

type NumberLogger = (n: number) => void;

type NumberLoggerProps = {
    logger: NumberLogger;
}

// or

type NumberLoggerProps = {
    logger: (n: number) => void;
}

// or

type NumberLoggerProps = {
    logger(n: number): void;
}

See more in the Typescript documentation.

  • Related