是否可以在不同屏幕中使用类型
发布: (2026年1月1日 GMT+8 06:47)
3 min read
原文: Dev.to
Source: Dev.to
问题
你在 toto.tsx 中定义了一个大型 TypeScript 类型,需要在其他页面(例如 titi.tsx)中复用。直接复制粘贴类型会导致维护困难,因为每次修改都必须在所有地方同步更新。
解决方案
将该类型提取到独立的模块中,在需要的地方导入即可。因为文件只包含类型定义——没有 JSX,使用普通的 TypeScript 文件(.ts)即可。
步骤
-
创建用于共享类型的专用文件
src/types/ └── stationTypes.ts -
将类型定义移动到该文件中
// src/types/stationTypes.ts export type STA = { response: number; id: number; method: string; next: string | null; fields: { id_field: number; field_name: string; field_longname: string; field_city: string; field_lat: number; field_lng: number; }[]; stations: { id_field: number; field_name: string; id_station: number; station_longname: string; station_type_awe: string; id_station_type: number; station_type_name: string; station_archive: number; lat: number; lng: number; alt: number; measures: { datasets: { data: { value: number; label: string; date: string; dataPointText: number; }[]; label: string; showLine: boolean; borderColor: string; backgroundColor: string; pointStyle: string; fill: boolean; borderWidth: number; pointRadius: number; type: string; }; labels: {}[]; unit: string; chartContainer: string; id_sensor_type: number; id_sensor: number; sensor_type: string; sensor_type_longname: string; sensor_type_awe: string; }[]; measures_found: number; station_found: number; latest_measure: string; }[]; map_center: { lat: number; lng: number; }; }; -
在需要的页面中导入该类型
// src/screens/toto.tsx import { STA } from '../types/stationTypes'; const MyComponent = () => { const data: STA = /* ... */; // component logic };// src/screens/titi.tsx import { STA } from '../types/stationTypes'; // 与在 toto.tsx 中相同方式使用 STA
为什么使用 .ts 文件?
- 该文件仅包含类型定义,没有 JSX,因此使用
.ts更合适。 - 将类型与 UI 代码分离有助于提升可读性和可复用性。
好处
- 单一来源 – 在一个地方修改类型即可。
- 类型安全 – 所有页面获得完全相同的定义。
- 项目结构更清晰 – 共享类型集中放在专门的文件夹中。