다른 화면에서 타입을 사용할 수 있나요
Source: Dev.to
Problem
toto.tsx에 정의된 큰 TypeScript 타입을 다른 화면(예: titi.tsx)에서도 재사용하고 싶습니다. 타입을 복사‑붙여넣기 하면 유지보수가 어려워집니다. 왜냐하면 변경 사항을 모든 곳에 일일이 반영해야 하기 때문입니다.
Solution
타입을 별도의 모듈로 추출하고 필요할 때마다 import 합니다. 타입 정의만 포함하고 JSX가 없으므로 일반 TypeScript 파일(.ts)이면 충분합니다.
Steps
-
공유 타입을 위한 전용 파일 만들기
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; }; }; -
필요한 화면에서 타입을 import
// 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'; // use STA the same way as in toto.tsx
Why a .ts file?
- 파일에 타입 정의만 포함되고 JSX가 없으므로
.ts가 적합합니다. - 타입을 UI 코드와 분리하면 가독성과 재사용성이 향상됩니다.
Benefits
- Single source of truth – 타입을 한 곳에서만 수정하면 됩니다.
- Type safety – 모든 화면이 동일한 정의를 사용합니다.
- Cleaner project structure – 공유 타입이 전용 폴더에 모여 프로젝트 구조가 깔끔해집니다.