Skip to content

[item 12] 래퍼 함수는 원본 함수와 완전히 같은 타입을 가져야 할까요? #12

Description

@bigcloud07

📖 참고한 페이지

p.75 ~ p.79

❓ 질문 / 문제

다음 함수는 요청에 실패하면 Error를 던지는 대신 반환하고 있습니다.

async function checkedFetch(
  input: RequestInfo,
  init?: RequestInit,
) {
  const response = await fetch(input, init);

  if (!response.ok) {
    return new Error(`Request failed: ${response.status}`);
  }

  return response;
}

반환 타입을 따로 선언하지 않았기 때문에 타입스크립트는 반환 타입을 다음과 같이 추론하고 오류를 발생시키지 않습니다.

Promise<Response | Error>

하지만 함수 표현식 전체에 typeof fetch를 적용하면 구현 단계에서 오류가 발생합니다.

declare function fetch(
  input: RequestInfo | URL,
  init?: RequestInit,
): Promise<Response>;

const checkedFetch: typeof fetch = async (input, init) => {
  const response = await fetch(input, init);

  if (!response.ok) {
    return new Error(`Request failed: ${response.status}`);
    // 오류: Error는 Response에 할당할 수 없음
  }

  return response;
};

checkedFetch와 같은 래퍼 함수는 항상 원본 함수의 typeof fetch를 사용해 완전히 동일한 타입 계약을 유지하는 것이 좋을까요?

반대로 오류를 값으로 반환하는 등 원본과 다른 동작을 의도했다면, typeof fetch를 재사용하지 않고 새로운 함수 타입을 정의하는 것이 더 적절할까요? 래퍼 함수가 원본 함수의 타입을 그대로 사용해야 하는 기준에 대해 이야기해 보면 좋겠습니다.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions