面试题答案
一键面试- 实现方案描述:
- 利用TypeScript的类型别名和接口扩展来基于
BaseProps
创建新类型。 - 通过重新导出类型而不是直接导入
BaseProps
所在模块,来切断直接依赖。 - 使用类型映射工具如
Pick
、Omit
、Partial
等对类型进行灵活的属性操作,再通过接口扩展来添加新属性。
- 利用TypeScript的类型别名和接口扩展来基于
- 关键代码:
- 基础类型定义文件(假设为
baseProps.ts
):
- 基础类型定义文件(假设为
// baseProps.ts
export type BaseProps = {
id: string;
createdAt: Date;
};
- 业务模块A(假设为
moduleA.ts
):
// moduleA.ts
// 重新导出BaseProps,而不是直接导入baseProps.ts模块
export { BaseProps } from './baseProps';
// 创建基于BaseProps的新类型
export type ModuleAProps = BaseProps & {
status: 'active' | 'inactive';
};
- 业务模块B(假设为
moduleB.ts
):
// moduleB.ts
// 同样重新导出BaseProps
export { BaseProps } from './baseProps';
// 利用类型映射和扩展创建新类型
import { Pick } from 'type - script';
export type ModuleBProps = Pick<BaseProps, 'id'> & {
updatedAt: Date;
};
- 使用模块A和模块B的类型:
- 在其他文件中使用ModuleAProps和ModuleBProps:
// main.ts
import { ModuleAProps } from './moduleA';
import { ModuleBProps } from './moduleB';
const aProps: ModuleAProps = {
id: '1',
createdAt: new Date(),
status: 'active'
};
const bProps: ModuleBProps = {
id: '2',
updatedAt: new Date()
};
这样通过重新导出基础类型,每个业务模块都不直接依赖baseProps.ts
模块,实现了类型依赖的切断,同时利用TypeScript的类型操作能力实现了灵活的属性映射与扩展。