问题如题,在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.container
、eat(food:string = this.food)
感觉不对,但是 tsc 能编译过
但是 vite 中打包 会有下面的错误提示:
类型设置为?:string呗,然后在函数内判断undefind自动调用属性值就行了。毕竟没实例化之前this是不存在的
已参与了 SegmentFault 思否社区 10 周年「问答」打卡 ,欢迎正在阅读的你也加入。