MST

星途 面试题库

面试题:TypeScript模块中如何实现跨模块共享类型定义

假设你正在开发一个TypeScript项目,有多个模块需要使用相同的自定义类型。请描述至少两种在不同模块间共享这些类型定义的方法,并给出简单代码示例。
29.4万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

1. 使用 export 导出类型定义

在一个单独的文件中定义类型,然后使用 export 导出,其他模块通过 import 导入。

types.ts

// 定义自定义类型
export type User = {
    name: string;
    age: number;
};

module1.ts

import { User } from './types';

const user: User = {
    name: 'John',
    age: 30
};

2. 使用 declare global(适用于全局类型声明)

在一个文件中使用 declare global 声明全局类型,这样在其他模块中无需导入即可使用。

globalTypes.ts

declare global {
    type Animal = {
        species: string;
        sound: string;
    };
}

module2.ts

const dog: Animal = {
    species: 'Dog',
    sound: 'Woof'
};

3. 使用 d.ts 文件(用于声明文件共享类型)

创建一个 .d.ts 文件来声明类型,其他模块会自动识别。

sharedTypes.d.ts

export type Point = {
    x: number;
    y: number;
};

module3.ts

import { Point } from './sharedTypes';

const point: Point = {
    x: 10,
    y: 20
};