假设我在另一个文件中有一个类,我想导入该类以使用其类型
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
中没有描述这种用法
这取决于importsNotUsedAsValues
编译器选项的值(在 tsconfig.json 中,或从命令行传入)。
如果它设置为(默认值),则导入接口(或仅在类型位置中使用的类)时和导入时remove
没有区别。在这两种情况下,编译后的 JavaScript 中都不会存在 import 或 require 语句(因此导入的模块中的任何副作用都不会被执行)。import
import type
如果此选项设置为preserve
,import
将导致编译器发出 import 语句,即使导入的类型是接口;import type
将不会。
如果此选项设置为error
,则必须使用; 导入接口import type
。使用import
会导致编译错误。
归档时间: |
|
查看次数: |
1956 次 |
最近记录: |