面试题答案
一键面试利用TypeScript模块化导出功能实现模块解耦与复用
- ES6 模块语法:使用
export
和import
语句。例如,在一个模块mathUtils.ts
中:
// mathUtils.ts
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
在其他模块中引入使用:
// main.ts
import { add, subtract } from './mathUtils';
const result1 = add(1, 2);
const result2 = subtract(5, 3);
- 默认导出:对于每个模块只有一个主要导出的情况,使用默认导出。例如,
user.ts
模块:
// user.ts
export interface User {
name: string;
age: number;
}
const defaultUser: User = { name: 'John', age: 30 };
export default defaultUser;
在其他模块引入:
// app.ts
import user from './user';
console.log(user.name);
- 重新导出:当需要重新组织模块结构时,重新导出很有用。例如,有一个
utils
文件夹,里面有多个工具模块stringUtils.ts
和numberUtils.ts
,在index.ts
中重新导出:
// stringUtils.ts
export function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
// numberUtils.ts
export function double(num: number): number {
return num * 2;
}
// utils/index.ts
export { capitalize } from './stringUtils';
export { double } from './numberUtils';
在外部模块引入:
// main.ts
import { capitalize, double } from './utils';
处理模块导出的类型声明以确保类型安全
- 类型与值一起导出:如上述
mathUtils.ts
和user.ts
示例,类型声明和函数、对象等值一起导出。这样在引入模块时,类型信息也随之引入,TypeScript 编译器可以进行类型检查。 - 使用
export type
:如果只想导出类型,而不导出值,可以使用export type
。例如:
// types.ts
export type Point = {
x: number;
y: number;
};
在其他模块使用:
// graphics.ts
import type { Point } from './types';
function drawPoint(point: Point) {
// 绘制点的逻辑
}
这里使用 import type
确保只引入类型,而不会引入实际的值,在编译为 JavaScript 时,不会产生额外的代码。
3. 类型声明文件(.d.ts
):对于一些第三方库或需要对外暴露类型但不希望暴露实现细节的模块,可以使用 .d.ts
文件。例如,创建 myLib.d.ts
:
// myLib.d.ts
export interface MyLibOptions {
option1: string;
option2: number;
}
export function myLibFunction(options: MyLibOptions): void;
在使用 myLib
的项目中,TypeScript 会根据这个类型声明文件进行类型检查,而无需知道实际的实现代码。