빌드시 다음과 같은 타입 오류가 발생했습니다.
./src/app/subscription/[id]/page.tsx:119:9
Type error: 'infra.stations.length' is possibly 'undefined'.
이 오류는 TypeScript가 infra.stations
배열이 존재하지 않을 가능성을 감지하여 발생했습니다.
if (infra?.stations?.length > 0) { ... }
if (Array.isArray(infra?.stations) && infra.stations.length > 0) { ... }
➤ 적용 이유:
Array.isArray()
를 사용하여 명확한 배열 유효성 검사를 수행합니다. 이를 통해 TypeScript가 stations
이 확실히 배열임을 인지하고, 런타임 오류를 방지할 수 있습니다.
다음과 같은 재사용 가능한 타입 가드를 추가했습니다:
function isValidInfraArray<T>(data: T[] | undefined | null): data is T[] {
return Array.isArray(data) && data.length > 0;
}
➤ 적용 이유:
이 타입 가드는 인프라 배열이 undefined
, null
이 아니며, 최소 하나 이상의 요소가 있는 배열임을 명확하게 타입스크립트에 전달합니다. 이를 통해 컴파일러가 data
를 명확히 배열로 추론할 수 있게 됩니다.
다음과 같은 인프라 데이터 접근 지점들에 robust null 체크를 적용하였습니다.
getInfraText()
헬퍼 함수예시 구현:
// 메타 설명 생성 예시
if (isValidInfraArray(infra.stations)) {
const nearestStation = infra.stations.sort((a, b) => a.distance - b.distance)[0];
descriptionParts.push(
`인근에 ${nearestStation.name}역(${Math.round(nearestStation.distance)}m)이 위치해 있습니다`
);
}
➤ 적용 이유:
동일한 robust null 체크 방식을 모든 관련 로직에 적용하여 코드의 일관성과 유지 보수성을 높이고, 타입 안정성을 보장합니다.