且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

TypeScript 定义函数的几种写法

更新时间:2022-09-07 11:56:29

写法1 - 使用 function 关键字

function greeter(fn: (a: string) => void) {

 fn("Hello, World");

}

function printToConsole(s: string) {

 console.log(s);

}

greeter(printToConsole);

(a: string) => void


上述语法的含义:表示一个函数,接收一个字符串作为输入参数,没有返回参数。


可以使用 type 关键字定义一个别名:


type GreetFunction = (a: string) => void;

1

Call signatures

使用 call signatures 给函数增加额外的属性。TypeScript 的 function 也是 value,和其他 value 一样。


注意:一定有 type 关键字。


源代码:

TypeScript 定义函数的几种写法TypeScript 定义函数的几种写法TypeScript 定义函数的几种写法TypeScript 定义函数的几种写法TypeScript 定义函数的几种写法TypeScript 定义函数的几种写法TypeScript 定义函数的几种写法TypeScript 定义函数的几种写法