From 08186f0efab99871e96ba0508274d55f74a8fda3 Mon Sep 17 00:00:00 2001 From: Alan Pierce Date: Sat, 29 Dec 2018 15:11:52 -0800 Subject: [PATCH] Add support for dynamic import() syntax in TS types (#380) Turns out this didn't work before, and I tried to use it when setting up code splitting in the playground. This is mostly based on `parseImportType` from the TypeScript codebase. --- src/parser/plugins/typescript.ts | 22 +++++++++++++++++++++- test/typescript-test.ts | 17 +++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/parser/plugins/typescript.ts b/src/parser/plugins/typescript.ts index 8f0a1e4f..4090476b 100644 --- a/src/parser/plugins/typescript.ts +++ b/src/parser/plugins/typescript.ts @@ -145,7 +145,24 @@ function tsParseThisTypeNode(): void { function tsParseTypeQuery(): void { expect(tt._typeof); - tsParseEntityName(); + if (match(tt._import)) { + tsParseImportType(); + } else { + tsParseEntityName(); + } +} + +function tsParseImportType(): void { + expect(tt._import); + expect(tt.parenL); + expect(tt.string); + expect(tt.parenR); + if (eat(tt.dot)) { + tsParseEntityName(); + } + if (match(tt.lessThan)) { + tsParseTypeArguments(); + } } function tsParseTypeParameter(): void { @@ -411,6 +428,9 @@ function tsParseNonArrayType(): void { case tt._typeof: tsParseTypeQuery(); return; + case tt._import: + tsParseImportType(); + return; case tt.braceL: if (tsLookaheadIsStartOfMappedType()) { tsParseMappedType(); diff --git a/test/typescript-test.ts b/test/typescript-test.ts index b14c79da..ccdb6836 100644 --- a/test/typescript-test.ts +++ b/test/typescript-test.ts @@ -1321,6 +1321,23 @@ describe("typescript transform", () => { let T = 3, b = 4, c = 5, d = 6; console.log(T, b, c, d); } + `, + ); + }); + + it("handles import() types", () => { + assertTypeScriptESMResult( + ` + type T1 = import("./foo"); + type T2 = typeof import("./bar"); + type T3 = import("./bar").Point; + type T4 = import("./utils").HashTable; + `, + ` + + + + `, ); });