TypeScript - Type Guard

오픈소스·2024년 4월 27일
0

typescript에서는 타입을 좁혀서 사용할 수 있다.

const response = await this.httpService.axiosRef
	.post<
        | {
          success: true;
          data: ResponseType;
        }
        | {
          success: false;
          errorType: ErrorType;
        }
	>(url);

Type Guard

    async pushNotice(id: number) {
        const notice = await this.repository.get(id);

      	// 여기까지는 notice: NoticeType
      
        if (!this.#validatePushableNotice(notice)) return;

		// 여기부터는 notice: PushableNoticeType
    }
        
    #validatePushableNotice(notice: NoticeType): notice is PushableNoticeType {
        if (this.isPushableNotice(notice)) return true;

        throw new Error('Not pushable notice');
    }        

0개의 댓글