본문 바로가기

Javascript

[TypeScript] overload 함수에서 No overload matches this call 에러

다음과 같이 오버로딩으로 된 코드를 작성했는데, No overload matches this call 이라는 error 가 발생 했다.

function func(str: 'hi'): string;
function func(str: 'bakery'): string;
function func(arg: 'hi' | 'bakery'): string {
  return arg;
}

function callExample(str: 'hi' | 'bakery') {
  return func(str); // error occurred!
}

급한 사람은 해결 방법부터 보자.

원인

에러 메시지를 자세히 보면 다음과 같다.

No overload matches this call.
Overload 1 of 2, '(str: "hi"): string', gave the following error.
Argument of type '"hi" | "bakery"' is not assignable to parameter of type '"hi"'.

요약하면 니가 만든 함수는 "hi" | "bakery" 같은 타입은 받을 수 없다는 에러다.

 

아니...분명 내가 만든 func 은 'hi', 'bakery' 둘 다 인자로 받을 수 있게 해놨는데 안된다니 라고 생각할 수 있지만, 저기서 "hi" | "bakery" 타입을 받게 선언한 것은 overload 를 구현한 함수다.

 

구현부는 직접적으로 호출될 수 없기 때문에, 위에 오버로드한 함수 중 하나를 호출해야 한다.

구현부가 아닌 함수 중에서는 "hi" | "bakery" 타입을 받는 함수가 없기 때문에 발생하는 에러다.

해결 방법

as any 같은 type assertion 을 걸어 해결할 수 있다. 아래처럼 인자에 as any 를 넘기면 해결 된다.

function callExample(str: 'hi' | 'bakery') {
  return func(str as any);
}

(overload 에 그냥 function func(str: 'hi' | 'bakery'):string 을 추가하는 방법도 있겠지만 그럼 오버로드를 하는 의미가 없지 않은가)

'Javascript' 카테고리의 다른 글

[You don't know JS] Chapter 4 - 강제변환  (0) 2021.04.14
Typescript generic & util  (0) 2021.04.08
return function  (0) 2021.03.24
[You don't know JS] Chapter2 - 값  (0) 2021.02.25
[You don't know JS] Chapter1 - 타입  (0) 2021.02.23