在TypeScript项目中,通常会将自定义类型存储在一个单独的文件中,然后在需要使用这些类型的地方进行导入。以下是一个示例解决方法:
// types.ts
export interface Person {
name: string;
age: number;
}
export type Fruit = 'apple' | 'banana' | 'orange';
// app.ts
import { Person, Fruit } from './types';
const person: Person = {
name: 'John',
age: 25
};
const fruit: Fruit = 'apple';
console.log(person);
console.log(fruit);
通过将自定义类型存储在一个单独的文件中,可以方便地在整个项目中共享和重用这些类型。