diff --git a/src/TokenProcessor.ts b/src/TokenProcessor.ts index 407414ea..1ea40516 100644 --- a/src/TokenProcessor.ts +++ b/src/TokenProcessor.ts @@ -168,13 +168,11 @@ export default class TokenProcessor { } removeInitialToken(): void { - this.resultCode += this.previousWhitespaceAndComments(); - this.tokenIndex++; + this.replaceToken(""); } removeToken(): void { - this.resultCode += this.previousWhitespaceAndComments().replace(/[^\r\n]/g, ""); - this.tokenIndex++; + this.replaceTokenTrimmingLeftWhitespace(""); } copyExpectedToken(tokenType: TokenType): void { diff --git a/test/sucrase-test.ts b/test/sucrase-test.ts index 5bd361fb..17e15e07 100644 --- a/test/sucrase-test.ts +++ b/test/sucrase-test.ts @@ -1052,6 +1052,32 @@ describe("sucrase", () => { ); }); + it("does not crash with nullish coalescing followed by TS `as`", () => { + assertOutput( + ` + setOutput(1 ?? 2 as any); + `, + 1, + {transforms: ["typescript"]}, + ); + }); + + it("correctly transforms nullish coalescing followed by TS `as`", () => { + assertResult( + ` + const foo = { + bar: baz ?? null as any + } + `, + `${NULLISH_COALESCE_PREFIX} + const foo = { + bar: _nullishCoalesce(baz, () => ( null )) + } + `, + {transforms: ["typescript"]}, + ); + }); + it("correctly transforms async functions using await in an optional chain", () => { assertResult( `