Try passing a function as a function argument in TypeScript

Try passing a function as a function argument in TypeScript

TypeScript is statically typed, so you need to specify types for arguments and variables.

This is a major difference from JavaScript and makes it less buggy.

Now let’s write about how to specify a function when specifying a function argument.

Simply put, all you need to do is to specify the types of function arguments and return values.

Concretely written, it is as follows.

function param(msg:string):string{
  console.log(msg);
  return msg;
}

function execute(aaa:(prm:string)=> string){
  aaa('aiueo');
}

execute(param);// Run here

The param function is a function that is passed as an argument. It has a type string as its first argument and returns a type string as its return value.

Since the execute function is a function that takes a param function as its argument, it is necessary to specify the type.

If it is a string type, it is as simple as “aaa:string”, but in the case of a function, it should be written as follows.

aaa:(prm:string)=> string

aaa is the argument name and (prm:string) is the argument portion of the param function. param function has a return value of string, so the return value is a string in the arrow function.

When the above code is executed, the following will be output to the console.

aiueo

If the return value is void, you can write void, and if there are two arguments, you can specify two types.

コメント

タイトルとURLをコピーしました