From 38c14c324f10ce4b0e23c2ae725771715aefe4e4 Mon Sep 17 00:00:00 2001 From: liuxingbaoyu <30521560+liuxingbaoyu@users.noreply.github.com> Date: Tue, 2 Apr 2024 22:47:10 +0800 Subject: [PATCH] fix: Correctly prints `{ [key in Bar]? }` (#16402) fix --- packages/babel-generator/src/generators/typescript.ts | 9 +++++---- .../test/fixtures/typescript/mapped-type/input.ts | 3 +++ .../test/fixtures/typescript/mapped-type/output.js | 5 ++++- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/babel-generator/src/generators/typescript.ts b/packages/babel-generator/src/generators/typescript.ts index cbb716f6ac4f..aae7f979d016 100644 --- a/packages/babel-generator/src/generators/typescript.ts +++ b/packages/babel-generator/src/generators/typescript.ts @@ -443,11 +443,12 @@ export function TSMappedType(this: Printer, node: t.TSMappedType) { this.token("]"); + if (optional) { + tokenIfPlusMinus(this, optional); + this.token("?"); + } + if (typeAnnotation) { - if (optional) { - tokenIfPlusMinus(this, optional); - this.token("?"); - } this.token(":"); this.space(); this.print(typeAnnotation, node); diff --git a/packages/babel-generator/test/fixtures/typescript/mapped-type/input.ts b/packages/babel-generator/test/fixtures/typescript/mapped-type/input.ts index 9c446e4ab103..611dd15d3377 100644 --- a/packages/babel-generator/test/fixtures/typescript/mapped-type/input.ts +++ b/packages/babel-generator/test/fixtures/typescript/mapped-type/input.ts @@ -1 +1,4 @@ type Bar = { [key in Foo] }; +type Foo2 = { [key in Bar]? }; +type Foo3 = { [key in keyof Bar]-? }; +type Foo4 = { [key in keyof Bar]+? }; diff --git a/packages/babel-generator/test/fixtures/typescript/mapped-type/output.js b/packages/babel-generator/test/fixtures/typescript/mapped-type/output.js index ebccaaab98fc..37b392920270 100644 --- a/packages/babel-generator/test/fixtures/typescript/mapped-type/output.js +++ b/packages/babel-generator/test/fixtures/typescript/mapped-type/output.js @@ -1 +1,4 @@ -type Bar = { [key in Foo] }; \ No newline at end of file +type Bar = { [key in Foo] }; +type Foo2 = { [key in Bar]? }; +type Foo3 = { [key in keyof Bar]-? }; +type Foo4 = { [key in keyof Bar]+? }; \ No newline at end of file