You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 16:45:43