typescript 에러(23.11.08)

#현업 #typescript

문제 상황

function TagPostList({ postList }: { postList: TagPost[] }) {
  const normalizeToTagPost = (
    postType: TagPost['postType'],
    post: PostDetail | CommunityDetail,
  ) => {
    return postType === 'CREATOR_POST'
      ? {
          postUuid: post.postUuid,
          hasAudio: Boolean(post.attachedAudio),
          title: post.title,
          body: post.body,
          thumbnailImageUrl: post.previewImageUrls?.[0],
          writerName: post.profile?.userName || '',
          displayDateTime: post.displayDateTime,
          viewCountCache: post.viewCountCache,
          commentsCount: post.postCommentsCount || 0,
          likedCountCache: post.likedCountCache,
          isSale: post.isSale,
          pointAmount: post.pointAmount,
          visible: post.visible,
        }
      : {
          postUuid: post.postUuid,
          thumbnailImageUrl: post.imgFilePaths?.[0],
          hasAudio: false,
          title: '',
          body: post.body,
          writerName: post.writerInfo?.userName || '',
          displayDateTime: '',
          viewCountCache: post.viewCountCache,
          commentsCount: post.postCommentsCount || 0,
          likedCountCache: post.likedCountCache,
        };
  };
type postType = 'CREATOR_POST' | 'COMMUNITY_POST';

post 에는 postType이 'CREATOR_POST' 일 때 postDetail type의 데이터로,

postType이 'COMMUNITY_POST' 일 때 communityDetail type의 데이터로 전달된다.

위와같은 코드를 작성했을때 예를들어 post.previewImageUrls 에서 previewImageurls라는 속성은 communityDetail type에 없다는 에러가 발생한다.

post의 타입을 PostDetail | CommunityDetail 로 또는의 조건이기 때문에 이슈가 어떤것이 문제인지 확인이 필요하다.

해결

export type PostType = 'CREATOR_POST' | 'COMMUNITY_POST';

export type Post<T extends PostType> = T extends 'CREATOR_POST'
  ? PostDetail
  : T extends 'COMMUNITY_POST'
  ? CommunityDetail
  : never;

PostType인자에 따라 CREATOR_POST 는 PostDetail 타입, COMMUNITY_POST는 CommunityDetail 타입으로 적용하도록 하여 해결했다.

...
  const postByCreatorPost = (post: PostDetail) => TagPostListData;

  const postByCommunityPost = (post: CommunityDetail) => TagPostListData;

  const normalizeToTagPost = <T extends TagPost['postType']>(
    postType: T,
    post: Extract<TagPost, { postType: T }>['post'],
  ): TagPostListData => {
    switch (postType) {
      case 'CREATOR_POST':
        return postByCreatorPost(post as PostDetail);
      case 'COMMUNITY_POST':
        return postByCommunityPost(post as CommunityDetail);
      default:
        return {} as TagPostListData;
    }
  };
...

또한 위와 같이 normalizeToTagPost 함수에서 swith case 문을 통해 postType에 따라 TagPostListData 타입을 리턴받을 수 있도록 처리하여 해결했다.

Last updated