Skip to content

Axios는 날짜 시각 형태의 문자열을 알아서 Date 객체로 변환하지 않는다

keeep-runnning edited this page Mar 18, 2023 · 1 revision

TypeScript를 쓰면서 API 응답에 대한 타입을 아래와 같이 정의했었다.

type LoadPostDetailResponse = {
  id: number;
  title: string;
  content: string;
  createdAt: Date;
  authorId: number;
  authorName: string;
};

그리고 runtime에 createdAt 프로퍼티를 사용하는데, Date 타입의 객체가 아니라 실제로는 "2023-03-17T06:07:22.452Z" 같은 string 타입의 값이었다.

응답받았을 때, JSON 형태의 http response body에 날짜-시각을 표현하는 문자열이 있는 경우, Axios가 알아서 Date 객체로 parse 하지 않기 때문이다.

사실 Axios의 문제는 아니고, JSON 문자열을 객체로 parse 할 때, 날짜-시각 형태의 문자열을 Date로 복구시키지 않기 때문이다.

// post.createdAt instanceof Date -> true
const post = { createdAt: new Date() };

// postStr -> '{"createdAt":"2023-03-18T04:27:23.732Z"}'
const postStr = JSON.stringify(post);

// typeof parsed.createdAt -> string
const parsed = JSON.parse(postStr);
  • post.createdAt은 Date 타입이었지만, post 객체를 JSON 형태의 문자열로 변환했다가 다시 객체로 변환했을 때, parsed.createdAt은 string 타입이 되어버린다.

그러므로 적당한 위치에서 날짜-시각을 표현하는 문자열을 Date 객체로 변환해서 사용해야 한다.