TS class 中方法的参数的默认值可以是 类的属性吗?

问题如题,在typescript playground 中写一个类似的,编译不会报错,但是默认参数也没有了,用 vite 打包,esbuild 编译的时候会报错,
实际代码:

protected stamp(elem: Element = this.container) {
  if (elem) {
    elem.setAttribute('data-cell-id', this.cellView.cell.id)
  }
}

模拟代码:

class Animal {
    food: string
    constructor(food: string) {
        this.food = food;
    }
    eat(food: string = this.food) {
    }
}

const animal = new Animal('banana');

animal.eat();

elem: Element = this.containereat(food:string = this.food)
感觉不对,但是 tsc 能编译过

但是 vite 中打包 会有下面的错误提示:

image.png

阅读 3k
2 个回答

在类和对象的方法中,this 是明确的,所以使用 this.xxx 作为默认值不会有问题,正如你试验代码那样。

但是为什么 tsc 能编译过但 vite 会出错呢?我也不知道,看一下是哪个工具报的错,然后修正一下它的配置,或者干脆直接把这个工具屏蔽掉。

已参与了 SegmentFault 思否社区 10 周年「问答」打卡 ,欢迎正在阅读的你也加入。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题