对接口进行“导入类型”而不是“导入”有什么意义吗?

Fil*_*ype 8 typescript

假设我在另一个文件中有一个类,我想导入该类以使用其类型

import type { Component } from "react";
Run Code Online (Sandbox Code Playgroud)

这是有道理的,因为 Component 是一个类。

如果我要导入接口怎么办,import type还需要吗?或者 Typescript 知道接口没有价值,因此type不需要。

import type { IHttpResponse } from "../lib/http";
Run Code Online (Sandbox Code Playgroud)

如果添加了编译器不会抱怨,并且文档type中没有描述这种用法

Jos*_*lva 9

这取决于importsNotUsedAsValues编译器选项的值(在 tsconfig.json 中,或从命令行传入)。

如果它设置为(默认值),则导入接口(或仅在类型位置中使用的类)时和导入时remove没有区别。在这两种情况下,编译后的 JavaScript 中都不会存在 import 或 require 语句(因此导入的模块中的任何副作用都不会被执行)。importimport type

如果此选项设置为preserveimport将导致编译器发出 import 语句,即使导入的类型是接口;import type将不会。

如果此选项设置为error,则必须使用; 导入接口import type。使用import会导致编译错误。