面试题答案
一键面试确保 ES6 原生模块和 TypeScript 模块协同工作
- 配置 TypeScript:在
tsconfig.json
中配置module
为esnext
,这样 TypeScript 会以 ES6 模块的方式进行解析。例如:
{
"compilerOptions": {
"module": "esnext",
// 其他配置项
}
}
- 导入 ES6 模块:在 TypeScript 模块中,可以像导入普通 ES6 模块一样导入 ES6 原生模块。例如,如果有一个 ES6 模块
example.js
导出一个函数:
// example.js
export function sayHello() {
console.log('Hello!');
}
在 TypeScript 模块中导入使用:
import { sayHello } from './example.js';
sayHello();
- 处理默认导出:对于 ES6 模块的默认导出,在 TypeScript 中导入语法也相同。例如,ES6 模块
defaultExample.js
:
// defaultExample.js
const message = 'This is a default export';
export default message;
在 TypeScript 中导入:
import message from './defaultExample.js';
console.log(message);
ES6 模块导出结构在 TypeScript 中使用时类型相关问题
- 类型定义缺失:ES6 模块本身没有类型定义,在 TypeScript 中使用时可能会缺少类型信息。解决方法是为 ES6 模块创建类型声明文件(
.d.ts
)。例如,对于上面的example.js
,可以创建example.d.ts
:
// example.d.ts
export function sayHello(): void;
- 类型兼容性:确保 ES6 模块导出的值的实际类型与在 TypeScript 中使用时的类型声明兼容。例如,如果 ES6 模块导出一个对象,在 TypeScript 中导入时要确保对象的属性类型匹配。假设 ES6 模块
objectExample.js
:
// objectExample.js
export const user = { name: 'John', age: 30 };
在 TypeScript 中,可以这样定义类型:
// 为导入的对象定义类型
interface User {
name: string;
age: number;
}
import { user } from './objectExample.js';
// 检查类型兼容性
const newUser: User = user;
- 泛型和函数重载:如果 ES6 模块导出的函数需要处理不同类型的参数或返回值,可能需要在 TypeScript 中使用函数重载或泛型来正确定义类型。例如,ES6 模块
funcExample.js
:
// funcExample.js
export function add(a, b) {
return a + b;
}
在 TypeScript 中,可以使用函数重载:
// funcExample.d.ts
export function add(a: number, b: number): number;
export function add(a: string, b: string): string;
export function add(a: any, b: any): any;
这样在 TypeScript 中使用 add
函数时会有正确的类型检查。