Skip to content

타입 단언을 사용해야 하는 경우 #7

@rookedsysc

Description

@rookedsysc

데이터베이스에는 Y or N으로 값이 표기되있으나 실제 데이터 타입은 string인 상황이다. 사람은 이걸 명확히 인지하지만 LSP는 이걸 인식하지 못한다.

export interface BadgeInfo {
  _id: string; // MongoDB ObjectId string
  badgeType: string;
  liveYn: 'Y' | 'N';
  duplicationYn: 'Y' | 'N';
  directYn: 'Y' | 'N';
  limit: number;
  startDate: string;
  endDate: string;
  subBadges?: SubBadgeInfo[];
}

아래 인터페이스에서 liveYn에 Y 또는 N을 넣었음에도 return badges에서 에러가 발생한다.

Type 'string' is not assignable to type '"Y" | "N"'.ts(2322)

  /**
   * 배지 메타데이터 목록 조회
   *
   * @param badgeIds 배지 ID 목록
   * @returns 배지 메타데이터 배열
   */
  private async fetchBadgeInfoList(badgeIds: string[]): Promise<BadgeInfo[]> {
    const badges = await Promise.all(
      badgeIds.map(async (badgeId) => {
        const badge =
          await this.badgeService.findBadgeFromMainOrHistory(badgeId);
        return {
          _id: badge.id,
          badgeType: badge.badgeType,
          liveYn: badge.liveYn === 'Y' ? 'Y' : 'N',
          duplicationYn: badge.duplicationYn === 'Y' ? 'Y' : 'N',
          directYn: badge.directYn === 'Y' ? 'Y' : 'N',
          limit: badge.limit,
          startDate: badge.startDate,
          endDate: badge.endDate,
          subBadges: badge.subBadges?.map((sub: any) => ({
            ...sub,
            unit: {
              ...sub.unit,
              es_ES: sub.unit.es_ES ?? undefined, // null이면 undefined로 변경
              zh_TW: sub.unit.zh_TW ?? undefined,
            },
          })),
        };
      }),
    );

    return badges;
  }

그래서 저 부분을 'Y' | 'N' 이라고 타입 단언을 해주면 해결이 된다.

          duplicationYn: (badge.duplicationYn === 'Y' ? 'Y' : 'N') as 'Y' | 'N',

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions