Typescript》》TS》》Typescript 3.8 import 、import type
Typescript 3.8
Typescript 3.8版本中专门引入了import type和export type
import type:****仅导入类型信息(如类、接口等),不引入运行时的值,编译后不会生成对应 JavaScript 代码。
主要用于类型检查,避免循环依赖和副作用。
**import:**导入模块中的值(变量、函数、类等)和类型,编译后会在生成的 JavaScript 代码中包含相应逻辑。
// 假设有一个模块 myModule.ts
export const myValue = 42;
export interface MyType {name: string;
}// 在另一个文件中导入
import { myValue, MyType } from './myModule';console.log(myValue); // 这行代码会在运行时执行
const obj: MyType = { name: 'example' }; // MyType 用于类型检查// 在这个例子中,myValue 是一个实际的值,会在运行时被导入和使用,而 MyType 是一个类型,用于编译时的类型检查。
// 假设有一个模块 myModule.ts
export const myValue = 42;
export interface MyType {name: string;
}// 在另一个文件中导入
import type { MyType } from './myModule';// myValue 不会被导入,因为它没有使用 import 语句(只有 import type)
const obj: MyType = { name: 'example' }; // MyType 用于类型检查
// 在这个例子中,MyType 被导入用于类型检查,但 myValue 没有被导入,因为它不是通过 import 而是通过 import type 导入的。因此,myValue 不会出现在编译后的 JavaScript 输出中。
混合导入(TypeScript 4.5+)
// 一行内同时导入类型和值(推荐)
import { useState, useEffect, type ComponentProps, type Ref } from 'react'const MyComponent = (props: ComponentProps<'div'>) => {const count: Ref<number> = ref(0)// ...
}
问自己这个问题:我需不需要在运行时(代码实际执行时)使用这个东西?
使用 import
只在写代码时用到(代码实际执行时,不使用)→ import type
// 这些在代码执行时真的需要存在
import { axios } from 'axios' // 要发网络请求
import { ref, computed } from 'vue' // 要创建响应式数据
import { utilityFunction } from './utils' // 要调用函数// 编译后:这些代码必须保留!// 这些只是给TS编译器看的"类型提示"
import type { User } from './types' // 只是定义数据形状
import type { RouteLocation } from 'vue-router' // 只是类型约束
import type { CSSProperties } from 'vue' // 只是样式类型// 编译后:这些代码会被完全删除!