• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

안녕하세요 제로초님

22.10.02 17:21 작성 조회수 181

0

interface Arr<T> {
  forEach(callback: (aaa: T) => void): void;
}
  const test: Arr<string> = ['hello', 'world'];
  console.log(
    'test',
    test.forEach((item) => console.log('item', item))
  );

안녕하세요 제로초님 하나 궁금한것이 생겨서 여쭤보고싶습니다.
위의 사진은 정상적으로 작동하는 코드입니다.

그런데 아래 사진 같은경우는 아래 사진에 첨부한 에러 메세지가 나오고 있습니다.

둘의 차이점은 함수 이름을 forEach 를 사용했을때 에러(X)
아래 사진은 함수 이름을 forEachTest로 사용 한 것 뿐인데
forEachTest 라는 함수는 현재 에러가 나고있는데요,
해당 코드에서
forEach와 forEachTest의 차이점은 무엇인가요??
제가 생각했을땐 forEach에서도 에러가 나야 하지 않을까?
였습니다.


해당 내용이 이해가 되질 않아서 답변주시면 감사하겠습니다.

 

interface Arr<T> {
  forEachTest(callback: (aaa: T) => void): void;
}  

  const test: Arr<string> = ['hello', 'world'];
  console.log(
    'test',
    test.forEachTest((item) => console.log('item', item))
  );


답변 1

답변을 작성해보세요.

0

interface Arr<T> extends Array<T> {
  forEachTest(callback: (aaa: T) => void): void;
}  

const test: Arr<string> = ['hello', 'world'] as Arr<string>;
console.log(
  'test',
  test.forEachTest((item) => console.log('item', item))
);
이렇게 as로 강제로 바꿔보세요. ['hello', 'world']가 Arr<string>이 아니어서 그렇습니다.
바스니카님의 프로필

바스니카

2023.01.01

interface Arr<T> {
  forEachTest(callback: (aaa: T) => void): void;
}

const test: Arr<string> = ["hello", "world"] as unknown as Arr<string>;
console.log(
  "test",
  test.forEachTest((item) => console.log("item", item))
);

이렇게 Array<T> 대신 Arr<T>로 생각하게 만들어도 에러가 안 발생하네요.