성장과정(dev)/Typescript ⊃Javascript

[typescript 유니온타입] 코드리뷰 후 메모 - typescript 매개변수을 유니온타입 배열형으로 정의 시 Array 함수 호출 시 에러

lowellSunny 2022. 7. 20. 10:49

기존에 이렇게 정의되어있었다.

const isExistTargetId = (target: Customer | Course, selectedTargets: Customer[] | Course[]) => {
      const found = Array.prototype.find.call(
        selectedTargets,
        (selectedTarget: Customer | Course) => selectedTarget.id === target.id,
      );
      return !!found?.id;
    };

 Array 함수를 이용하는데 call 을 사용한 이유는  다음과 같이 This expression is not callable 이라는 에러가 발생했기 때문이다.

분명히 selectedTargets 는 어떤 타입이든 [] 배열로 정의되어있음에도 불구하고 왜 This expression is not callable 이라는 에러가 뜰까?

찾아보니 typescript 쪽 에러이며 , 버전업하면서 지원해주는 함수가 많아지고 있다고 한다.

수정 후 : (Customer | Course)[]) 이런식으로 정의하니 에러가 사라졌고, 유무만 반환하면 되기 때문에 findIndex로 바꾸어버렸다.

const isExistTargetId = (target: Customer | Course, selectedTargets: (Customer | Course)[]) => {
      const existTargetIndex = selectedTargets?.findIndex(
        (selectedTarget: Customer | Course) => selectedTarget?.id === target?.id,
      );
      return existTargetIndex > -1;
    };

 

참고로 현재는 (Customer[] | Course[]) 이런식으로 썼을 때 findIndex는 저런 에러가 발생하지 않고 잘 되고, find 는 지원하지 않는다.

검색 하다가 참고한 사이트 (마이크로소프트에서 이슈로 올렸었군요)

https://github.com/microsoft/TypeScript/issues/36390#issuecomment-971992590

 

--- 추가적으로 기억할 것 ---

* instanceof

class 는 typeof 를 사용해도 무조건 "object" 를 반환하기 때문에 이럴 때는 Instanceof 를 사용한다. 

 

* 선택적 매개변수 y?: 이런식으로 정의한다.

function f(x: number, y?: number) {
    //내용..
}