如何在TypeScript中编写嵌套函数?求JS闭包转TS方案
TypeScript中编写嵌套函数(闭包)的方法
针对你提供的JavaScript闭包代码,转换为TypeScript时核心是处理好this的指向和类型注解,以下是两种可行的转换方案:
方案一:使用箭头函数继承外层this
这种方式可以避免普通函数调用时this指向异常的问题,同时添加类型定义让TS做类型检查:
// 定义当前上下文的类型接口 interface ComponentContext { getClaimNotices: () => void; gridServices: { get: () => void; }; } // 定义$scope的类型接口 interface Scope { setDataLoading: (isLoading: boolean) => void; // 如果需要启用注释的方法,补充对应类型 // gridServicesReciepts: { get: () => void }; } // 声明$scope变量(实际项目中可能已通过框架注入) declare const $scope: Scope; const postPonedMethod1 = function(this: ComponentContext) { // 箭头函数自动捕获外层的this const postPonedMethod2 = () => { this.getClaimNotices(); this.gridServices.get(); // $scope.gridServicesReciepts.get(); $scope.setDataLoading(false); }; postPonedMethod2(); };
方案二:手动绑定this(保留普通函数写法)
如果偏好使用普通函数,可以在调用内层函数时显式绑定外层的this:
interface ComponentContext { getClaimNotices: () => void; gridServices: { get: () => void; }; } interface Scope { setDataLoading: (isLoading: boolean) => void; } declare const $scope: Scope; const postPonedMethod1 = function(this: ComponentContext) { const postPonedMethod2 = function() { this.getClaimNotices(); this.gridServices.get(); $scope.setDataLoading(false); }; // 调用时绑定外层的this postPonedMethod2.call(this); };
关键说明
- TypeScript中嵌套函数的写法和JavaScript类似,但必须明确
this的类型,否则TS会抛出类型错误。 - 定义上下文和
$scope的类型接口,是TypeScript类型安全的核心,能提前发现潜在的调用错误。
内容的提问来源于stack exchange,提问作者Azeem
相关产品推荐
相关产品推荐

