Babel typescript操作符重载插件



我是babel的新手,但我熟悉typescript,我发现了这个babel操作符重载的例子,但它是javascript,我想在我的typescript项目中使用操作符重载功能

我遵循这个typescript Babel starter项目,并试图将它与上面的操作符重载示例项目混合,但是当我试图构建时,typescript编译器给出了以下错误:

> tsc --emitDeclarationOnly
src/index.ts:30:12 - error TS2365: Operator '+' cannot be applied to types 'import("/TypeScript-Babel-Overload/src/index").Point' and 'import("/TypeScript-Babel-Overload/src/index").Point'.
30 const p3 = p1 + p2
~~~~~~~

Found 1 error.

我在github上的示例项目:https://github.com/cjbd/TypeScript-Babel-Overload

如何使它工作?请帮忙,谢谢!

更新:

感谢@Sly_cardinal,@ts-ignoreworks,项目通过编译,我已经更新了github

问题:我可以全局忽略所有操作符错误吗?因为我打算经常使用这个

感谢@AlekseyL。我忘了启用下面的插件,代码现在正在工作

'operator-overloading enabled'
class Point {
constructor(x: number, y: number) {
this.x = x
this.y = y
}
[Symbol.for('+')](other: Point) {
const x = this.x + other.x
const y = this.y + other.y
return new Point(x, y)
}
x: number;
y: number;
}
// Check overloads work
const p1 = new Point(5, 5)
const p2 = new Point(2, 3)
// @ts-ignore: operator overloading
const p3 = p1 + p2;
console.log(`p3 = (${p3.x}, ${p3.y})`)
$ node lib/index.js
p3 = (7, 8)

TypeScript不允许操作符重载,这就是为什么你会得到这个错误。

尝试使用// @ts-ignore注释来抑制该行的错误。

仍然可以让TypeScript发出你的类型定义,但允许babel处理到JavaScript的编译。但是,您可能会得到奇怪的、不完整的或无效的类型定义。

(参见如何使用ts-ignore的说明:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html#suppress-errors-in-ts-files-using--ts-ignore-comments)

在使用操作符重载或类似的不受支持的JavaScript语法扩展时,您需要使用ts-ignore注释。

最新更新