TypeScript中使用call导致this隐式any类型错误的修复方案
修复TypeScript中
this隐式any类型错误的方案 你遇到的问题根源在于那个匿名函数里的this没有明确的类型注解,TypeScript无法自动推断它的类型,因此抛出了隐式any的错误。下面给你几种可行的修复方案,按代码改动大小排序:
方案1:给匿名函数添加this类型注解
TypeScript允许在函数的第一个参数位置声明this的类型(这个参数仅用于类型检查,不会在实际执行时被传递),直接给匿名函数加上this: Date的注解即可:
const getCurrentTime = () => { const date = new Date(); const d = Date.prototype; const funcs = [ d.getFullYear, function(this: Date) { // 这里添加this的类型注解 return d.getMonth.call(this) + 1; }, d.getDate, d.getHours, d.getMinutes, ]; return funcs.reduce( (prevStr, current) => `${prevStr}-${current.call(date)}`, '', ); };
这种改动最小,完全保留了你原有的代码结构,TypeScript现在能明确知道这个函数里的this指向Date实例,错误自然消失。
方案2:用箭头函数替代匿名函数
箭头函数不会绑定自己的this,而是继承外层作用域的上下文,而且我们可以直接在箭头函数里指定call的上下文为外部的date,彻底避开this的类型问题:
const getCurrentTime = () => { const date = new Date(); const d = Date.prototype; const funcs = [ d.getFullYear, () => d.getMonth.call(date) + 1, // 箭头函数直接使用外部的date d.getDate, d.getHours, d.getMinutes, ]; return funcs.reduce( (prevStr, current) => `${prevStr}-${current.call(date)}`, '', ); };
这里注意:箭头函数本身不需要call(date)来绑定this,但因为funcs数组里的其他元素都是Date原型上的方法(需要call绑定上下文),所以reduce里的current.call(date)对箭头函数也能正常生效(箭头函数的call不会改变this,但不影响执行逻辑)。
方案3:简化整个函数逻辑(更推荐)
其实你原有的代码逻辑可以简化成更直观的写法,完全避开this相关的问题,同时代码可读性更高:
const getCurrentTime = () => { const date = new Date(); return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}-${date.getHours()}-${date.getMinutes()}`; };
这种写法直接调用date实例的方法,不需要借助Date.prototype和call,代码更简洁,也不会有任何类型报错。
内容的提问来源于stack exchange,提问作者crazyones110
相关产品推荐
相关产品推荐

