Home > OS >  How the Typescript function parameter works?
How the Typescript function parameter works?

Time:01-11


function greeter(fn: (a: string ) => void) {
  fn("Hello, World");
}
 
function printToConsole() {
  console.log(1);
}
 
greeter(printToConsole);

I am new in typescript and the above really confuses me.

The function greeter needs another function as parameter which takes a string

The function printToConsole is a function without any parameter.

Why greeter can accept printToConsole as a parameter?

I expect an error from complier

CodePudding user response:

After a bit of research, it looks like that printToConsole doesn't need a parameter because you just simply print the number "1" and you don't actually use the argument passed to fn.
TypeScript allows this kind of behavior because the callback functions signature and the function you give as an argument do the same thing. You don't use the argument defined in the callback's signature, so you could say that fn has no parameter as well and both functions return nothing.

CodePudding user response:

you can define a Generics to calculate the incoming parameters

function greeter<T extends (a: string) => void>(fn: ParamsType<T>) {
  fn('Hello, World');
}

function printToConsole(a: string) {
  console.log(1);
}

greeter(printToConsole);

type ParamsType<T> = T extends (...args: infer Args) => any ? (Args[0] extends string ? T : Error) : Error;


  • Related