TypeScript回调函数详解

TypeScript回调函数详解 什么是 TypeScript 中的回调函数callback函数定义为作为参数传递给另一个函数的函数然后在外部函数内部调用该函数以完成所需的例程或操作。function outerFunction(callback: () void) { callback(); }以下是开发者社区中在 TypeScript 中定义函数回调类型的流行方法。TypeScript 中回调类型接口的使用TypeScript 支持通过接口声明来定义变量或函数的通用结构这种机制特别适用于规范函数的调用签名类型。让我们考虑以下代码const greeting (message:string) console.log(Hello ${message}); interface definitionInterface{ (message:string):void; } function sayHello(callback: definitionInterface) { callback(World!) } sayHello(greeting);interface定义了definitionInterface的调用签名其中callback参数类型为字符串返回类型为 void表示回调函数的返回值将被忽略。让我们开始看看回调细节更改函数签名即用数字而不是字符串打招呼将显示类型为字符串不可分配给类型编号的错误。它创建了一个强大的回调而不是像我们通常在 JavaScript 中那样传递函数在 TypeScript 中使用泛型作为回调类型TypeScript 中的 Generic 允许我们使用如下参数泛化回调。它给你的好处是每次你需要一个带参数的回调时一次又一次地用新名称定义一个新接口。回调在大多数情况下不会返回任何值因此 typeTwo 类型默认设置为 void。但是如果你想从回调函数返回一个值你可以指定 typeTwo 类型。interface callackOneParametertypeTwo, typeTwo void { (param1: typeTwo): typeTwo; }让我们看看下面两个使用 Generic 接口的示例代码。interface callBackOneParametertypeOne, typeTwo void { (param1: typeOne): typeTwo; } function greet(message: string) { console.log(${message}, how are you doing?) } function sayHello(callback: callBackOneParameterstring) { callback(Hello) } sayHello(greet)此代码生成以下结果。带类型interface callBackOneParametertypeOne, typeTwo void { (param1: typeOne): typeTwo; } function greet(message: string) { return ${message}, how are you doing? } function sayHello(greet: callBackOneParameterstring, string) { let message greet(Hi Ibrahim!) console.log(message) } sayHello(greet)上面的代码生成以下结果在 TypeScript 中使用 Type 关键字声明回调类型在 TypeScript 中type 关键字声明了一个 type 别名。因此在 type 关键字的帮助下你可以声明你的回调类型如下所示。type callBackFunction () void;这声明了一个不接受任何参数并且不返回任何内容的函数。然后一个可以接受零到更多任何类型的参数并且不返回任何内容的函数将如下所示。//Then you can utilize it as let callback: CallbackFunctionVariadic function(...args: any[]) { // do some stuff };一个函数可以接受任意数量的参数并返回一个 void 值。type CallbackFunctionVariadicAnyReturn (...args: any[]) any;