聊聊TypeScript中的import type

670 阅读2分钟

大家好,今天我们要探讨的是TypeScript中的一个语法特性:import type

什么是import type?

在TypeScript中,import type是一种特殊的导入形式,它只导入类型,而不导入值。这意味着在运行时,这种导入不会产生任何实际的代码。这对于避免在JavaScript输出中产生不必要的代码,或者解决循环依赖问题非常有用。

import type的使用

让我们来看一些import type的使用例子。

导入接口

首先,我们需要一个接口来导入。让我们创建一个my-module.ts文件,并在其中定义一个接口MyInterface:

my-module.ts:

export interface MyInterface {
  name: string;
  age: number;
};

然后,我们可以使用import type来导入这个接口:

import type { MyInterface } from './my-module';

let personMyInterface;
person = { name'CursorBot'age4 };

在这个例子中,MyInterface只能用作类型注解,不能用作值。

导入函数类型

我们也可以导入函数类型:

my-module.ts:

export type MyFunction = (x: number, y: number) => number;

使用之

import type { MyFunction } from './my-module';

let addMyFunction;
add = (x, y) => x + y;

在这个例子中,MyFunction只能用作类型注解,不能用作值。

导入类类型

我们还可以导入类类型:

my-module.ts:

export class MyClass {
  constructor(public name: string, public age: number) {
      // 注意这里有具体实现
  }
}

使用之

import type { MyClass } from './my-module';

let createInstance(name: string, age: number) => MyClass;

createInstance = (name, age) => {
  return new MyClass(name, age);
};

在这个例子中,MyClass只能用作类型注解,不能用作值。

导入枚举类型

最后,我们还可以导入枚举类型:

my-module.ts:

export enum MyEnum {
  Foo,
  Bar,
  Baz,
}

使用之

import type { MyEnum } from './my-module';

let myEnumValueMyEnum;
myEnumValue = MyEnum.Foo;

在这个例子中,MyEnum只能用作类型注解,不能用作值。

结语

总的来说,import type是TypeScript中一个非常有用的特性,它可以帮助我们更好地组织和管理我们的类型。虽然它可能看起来有点神秘,但只要你掌握了它的用法,就会发现它其实是一个非常实用的工具。


注意:

  • 在上述示例中,尽管我们可以使用import type导入类和枚举类型,
  • 但实际上,类和枚举在TypeScript中既是类型也是值
  • 因此,如果你需要在运行时使用类或枚举,你应该使用常规的import语句,而不是import type