面试题答案
一键面试常规类型导入方式
在 TypeScript 中,从模块 A 导入类型到模块 B,可使用 import { type } from 'path/to/moduleA';
语法。如果模块 A 默认导出一个类型,也可使用 import type from 'path/to/moduleA';
优化命名空间避免命名冲突
- 使用别名:导入时通过
as
关键字给导入的类型取别名。例如:import { SomeType as MyAlias } from 'path/to/moduleA';
- 使用命名空间导入:
import * as ns from 'path/to/moduleA';
然后通过ns.SomeType
使用类型,这样可将所有导入类型封装在ns
命名空间下。
代码示例
模块 A (moduleA.ts)
// 定义类型
export type User = {
name: string;
age: number;
};
export type Role = 'admin' | 'user' | 'guest';
模块 B (moduleB.ts)
// 使用别名避免命名冲突
import { User as AppUser, Role } from './moduleA';
const user: AppUser = {
name: 'John',
age: 30
};
const userRole: Role = 'user';
// 使用命名空间导入
import * as types from './moduleA';
const anotherUser: types.User = {
name: 'Jane',
age: 25
};
const anotherRole: types.Role = 'guest';