面试题答案
一键面试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
};