如何在TypeScript Playground中解决函数内this隐式any类型错误?
解决TypeScript中'this'隐式为'any'的错误
针对你遇到的问题,有几种实用的修改方式:
方式一:显式标注函数的this参数
先定义实例的接口类型,然后在函数的第一个参数位置标注this的类型(这个参数不会被实际传入,仅用于TypeScript类型校验):
interface MyNodeInstance { val?: number; next?: unknown; } const MyNode = function(this: MyNodeInstance, val?: number, next?: unknown) { this.val = val; this.next = next; }
方式二:改用Class语法
TypeScript对类的类型支持更原生,无需手动处理this的类型问题,代码更简洁规范:
class MyNode { val?: number; next?: unknown; constructor(val?: number, next?: unknown) { this.val = val; this.next = next; } }
方式三:修正JSDoc注解(若坚持使用函数表达式)
你之前的JSDoc无效是因为@this typeof MyNode指向的是函数本身的类型,而非实例类型。需要先定义实例的类型,再给@this指定正确的目标类型:
/** * @typedef {Object} MyNodeInstance * @property {number} [val] * @property {unknown} [next] */ /** * @constructor * @this {MyNodeInstance} */ const MyNode = function(val?: number, next?: unknown) { this.val = val; this.next = next; }
内容的提问来源于stack exchange,提问作者wongx
相关产品推荐
相关产品推荐

