Error

[Typescript] undefined' is not assignable to type 'ArrayLike<string> 에러 해결

MOMOBOB 2024. 9. 12. 21:24
반응형

Error

Typescript에서 Set객체를 string array로 Array.from을 이용해서 변환시 아래와 같은 에러가 발생함.

No overload matches this call.
  Overload 1 of 4, '(iterable: Iterable<string> | ArrayLike<string>): string[]', gave the following error.
    Argument of type 'Set<string> | undefined' is not assignable to parameter of type 'Iterable<string> | ArrayLike<string>'.
      Type 'undefined' is not assignable to type 'Iterable<string> | ArrayLike<string>'.
  Overload 2 of 4, '(arrayLike: ArrayLike<string>): string[]', gave the following error.
    Argument of type 'Set<string> | undefined' is not assignable to parameter of type 'ArrayLike<string>'.
      Type 'undefined' is not assignable to type 'ArrayLike<string>'

 


 

Solution

Set<string> | undefined 타입이 Array.from()에 전달되었기 때문에 문제가 발생

Set이 undefined일 수 있다는 가능성이 있기 때문에 발생한 오류로 undefined를 처리할 수 있도록 조건부로 Set을 확인하거나, 기본값을 제공하면 됨.

 

1: undefined 체크

const mySet: Set<string> | undefined = new Set<string>(['apple', 'banana', 'cherry']);

// undefined 체크
const stringArray: string[] = Array.from(mySet ?? []);

console.log(stringArray); // ['apple', 'banana', 'cherry']

 

2: 기본값 제공

const mySet: Set<string> | undefined = new Set<string>(['apple', 'banana', 'cherry']);

// 기본값으로 빈 Set 제공
const stringArray: string[] = Array.from(mySet || new Set());

console.log(stringArray); // 빈 배열 출력 []

 

 

끝.

 


Thank you!

반응형