【问题标题】:Is `import type` equivalent to `import()``import type` 是否等同于 `import()`
【发布时间】:2021-03-28 00:11:59
【问题描述】:

import type { Foo, Bar as Baz } from './'

type Foo = import('./').Foo
type Bar = import('./').Baz

等价的?

请注意,此上下文中的 import() 不是动态导入,而是在 TypeScript 2.9 中引入的 import types。您可以在TypeScript playground 中输入这两个示例以验证语法/类型是否有效。

我想使用import type,但也想为 TS

如果上述断言为真,我可以对发出的声明文件应用 AST 转换。

【问题讨论】:

  • 请注意,这些不是动态导入,而是 TypeScript 2.9 中引入的附加功能:typescriptlang.org/docs/handbook/release-notes/…
  • 啊有趣。也就是说,这些类型导入适用于不能使用正常导入的非模块脚本,在这种情况下它们不能互换。

标签: typescript


【解决方案1】:

虽然它们在实践中经常可以互换,但它们并不等价。根据具体情况,有两个不同之处可能很重要。

import type 使文件成为模块。

TypeScript 编译器通过存在任何 importexport 声明来确定 TypeScript 文件的顶级范围是模块范围还是全局范围(即文件是模块还是脚本)。 import type 算作导入声明,因此如果它是文件中唯一的导入/导出语句,则为其替换类型别名会将文件从模块更改为脚本。这样做的实际含义是,如果您有一个需要全局的文件(通常是 .d.ts 文件),但又想从模块中引用类型,那么您将无法使用 @ 987654326@.

import type 可以引用值和命名空间的含义。

当您使用 type Foo = import('./').Bar 声明类型别名时,Foo纯粹是一种类型,即使 Bar 具有类型和值含义(例如 class Bar {})。在此声明中,您已经完全放弃了 Bar 的价值方面。 import type 实际上引用了完整的 Bar 符号及其所有含义,它只是设置了一个语法检查,以确保您永远不会在会被发送到 JS 的位置使用它(因为 import 语句将在 JS 中被删除)。这在几个地方很重要,最容易用一个例子来展示:

import type { EventEmitter as EE1 } from "events";
type EE2 = import("events").EventEmitter;

// Ok, because `declare` means `Foo1` is not actually referenced
// in an emitting position.
declare class Derived1 extends EE1 {}

declare class Derived2 extends EE2 {}
//                             ^^^
// Error: 'EE2' only refers to a type, but is being used as a value here.

type EventEmitterCtor1 = typeof EE1; // Ok
type EventEmitterCtor2 = typeof EE2;
//                              ^^^
// Error: 'EE2' only refers to a type, but is being used as a value here.

const x = EE1;
//        ^^^
// Error: 'EE1' cannot be used as a value because it was imported using 'import type'

const y = EE2;
//        ^^^
// 'EE2' only refers to a type, but is being used as a value here.

(Playground link)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-12
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2014-04-10
    相关资源
    最近更新 更多