[TS] Property 'map' does not exist on type 문제

2022. 10. 2. 10:36

ts에서 내가 interface를 정의하여 타입을 지정한 배열에서, map을 사용해야 하는 상황이 발생했는데 이때 'Property 'map' does not exist on type' 이라는 문구가 뜨며 문제가 발생하였다. 이 타입을 지정해서 배열로 인식하지 못하여 map을 사용할 수 없다는 것이다. 그래서 이것에 대한 해결 방안으로 아래와 같은 방법을 시도했다.

 

문제 원인

"Property 'map' does not exist on type" 오류 map()는 배열이 아닌 값에 대해 메서드를 호출할 때 발생한다. 오류를 해결하려면 map()배열의 메서드만 호출하거나 메서드를 호출하는 변수의 유형을 수정해야 한다.

const person = {
  name: 'Kim',
  age: 25,
};

person.map();

// Error message: Property 'map' does not exist on type
// '{ name: string; age: number; }'.ts(2339)

 

이와 같이 객체도 될 수 있고 배열도 될 수 있는 경우에는 아래와 같이 사용한다.

const person = {
  name: 'Kim',
  age: 25,
};

const result = Object.keys(person).map((key) => {
  return { [key]: obj[key as keyof typeof obj] };
});

console.log(result); // result: [{name: 'Kim'}, {age: 25}]

 

 

아니면 isArray를 사용하여 미리 한 번 체크를 해주는 형식으로 사용할 수도 있다.

const isItArray = Math.random() > 0.5 ? [1, 2, 3] : { name: 'Kim DoDo' };

if (Array.isArray(isItArray)) {
  const result = isItArray.map((element) => {
    return element * 2;
  });

  console.log(result); // [2, 4, 6]
}

 

그러나 나는 다른 방법은 선택했다. 이와 같은 방법으로 처리를 해주었다.

let data : MyModel[] = props.data[props.keywordIndex];
    const copyData = JSON.parse(JSON.stringify(data));

    data = copyData.map((val:MyModel) => { 
        val.PcCnt = isNaN(Number(val.mobilCnt)) ? Number(String(val.PcCnt).replaceAll("< ", "")) : val.PcCnt
        
        return val
    })

 

JSON.parse()

  • parse 메소드는 string 객체를 json 객체로 변환

JSON.stringify

  • stringify 메소드는 json 객체를 String 객체로 변환

 

이렇게 해서 문제를 해결했다!

 

참고글

 

Property 'map' does not exist on type Object

type MyStructure = Object[] | Object; const myStructure: MyStructure = [{ foo: "bar" }]; myStructure.map(); // Property 'map' does not exist on type 'MyStructure'. any The library either deliver...

stackoverflow.com

 

Property 'map' does not exist on type in TypeScript | bobbyhadz

The error "Property 'map' does not exist on type" occurs when we call the `map()` method on a value that isn't an array. To solve the error, make sure to only call the `map()` method on arrays or correct the type of the variable on which you call the metho

bobbyhadz.com

 

BELATED ARTICLES

more