在Typescript中返回this的对象方法的类型应该是什么?



假设我有一个像这样的对象:

const console = {
write(text: string) {
/* logic */
return this;
},
writeLine(text: string) {
/* logic */
return this;
}
};
write的返回类型应该是什么?和writeLine

方法吗?我知道我们可以定义一个接口并将其设置为返回类型,但是还有其他方法来设置引用对象的类型吗?

可以这样显式地定义返回类型:

const _console = {
write(text: string): typeof this {
/* logic */
return this;
},
writeLine(text: string): typeof this {
/* logic */
return this;
}
};

游乐场

或者您可以将console定义为一个类,而只使用this:

class Console {
write(text: string): this {
/* logic */
return this;
}
writeLine(text: string): this {
/* logic */
return this;
}
};

游乐场

我希望它能让ESLint高兴:D

最新更新