简体   繁体   中英

babel typescript operator overloading plugin

i'm new to babel but i'm familiar with typescript , i found this babel operator overloading example , but it's for javascript , i want to use operator overloading feature in my typescript project

i followed this typescript babel starter project and tried to mix it with above operator overloading example project, but when i tried to build, the typescript compiler gives below errors:

> 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.

my sample project on github: https://github.com/cjbd/TypeScript-Babel-Overload

how to make it work? please help, thank you!


update:

thanks to @Sly_cardinal, @ts-ignore works, the project complied throught, i've updated the github

question: can i ignore all the operator errors, globally? as i plan to use this a lot

thanks to @AlekseyL. , i forgot to enable the plugin below code is working now

'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 doesn't allow operator overloading which is why you're getting that error.

Try using the // @ts-ignore comment to suppress the error on that line.

That should still let TypeScript emit your type definitions but allow babel to handle the transpilation to JavaScript. You might end up with weird, incomplete, or invalid type definitions though.

(See notes on how to use ts-ignore: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html#suppress-errors-in-ts-files-using--ts-ignore-comments )

You would need to use the ts-ignore comment anywhere you are using operator overloading or similar unsupported extensions to the JavaScript syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM