[TS] Superstruct

  • API 응답 값의 타입이 string 이어야 하는데 number 가 들어오는 것과 같이 잘못된 타입이 전달될 수 있다. 그러나 타입스크립트는 정적 검사 도구로 런타임에서 발생하는 오류는 찾아낼 수 없다. 런타임에 API 응답의 타입 오류를 방지하려면 Superstruct 같은 라이브러리를 사용하면 된다.
  • Superstruct은 런타임에서의 데이터 유효성 검사를 통해 개발자와 사용자에게 자세한 런타임 에러를 보여주기 위해 고안되었다. 이를 사용하면 인터페이스 정의와 자바스크립트 데이터의 유효성 검사를 쉽게 할 수 있다.

사용법

  • assert : 유효하지 않을 경우 에러를 던진다.
  • is : 유효성 검사 결과에 따른 boolean 값을 반환한다.
  • validate : [error, data] 형식의 타입을 반환한다. 유효하지 않을 때는 에러 값이 반환되고 유효한 경우에는 첫 번째 요소로 undefined , 두 번째 요소로 data value가 반환된다.
import {
  assert,
  is,
  validate,
  object,
  number,
  string,
  array,
} from 'superstruct';

// 데이터 명세, 스키마
const Article = object({
  id: number(),
  title: string(),
  tags: array(string()),
  author: object({
    id: number(),
  }),
});

const data = {
  id: 34,
  title: 'Hello World',
  tags: ['news', 'features'],
  author: {
    id: 1,
  },
};

// 데이터 유효성 검사를 도와주는 모듈
assert(data, Article);
is(data, Article);
validate(data, Article);

with 타입스크립트

  • Infer 를 사용하여 기존 타입 선언 방식과 동일하게 타입을 선언할 수 있다.
import { Infer, object, number, string, array } from 'superstruct';

const Article = object({
  id: number(),
  title: string(),
  tags: array(string()),
  author: object({
    id: number(),
  }),
});

type Article = Infer<typeof Article>;
  • assert 메서드를 통해 데이터와 타입이 매칭되는지 확인한다.
type Article = {
  id: number;
  title: string;
};

const Article = object({
  id: number(),
  title: string(),
});

function isArticle(article: Article) {
  assert(article, Article);
  console.log('검사 성공!');
}

런타임 응답 타입 검증

  • 타입스크립트는 컴파일타임에 타입을 검증하는 역할을 한다. 따라서 타입스크립트만으로는 실제 서버 응답 형식과 명시한 타입이 일치하는지 확인할 수 없다.
  • Superstruct를 사용하여 API 응답으로 가져온 listItems 를 실제 런타임에서 유효성 검사를 진행한다.
import { assert, object, string } from 'superstruct';

const ListItem = object({
  id: string(),
  content: string(),
});

function isListItem(listItems: ListItem[]) {
  listItems.forEach((listItem) => assert(listItem, ListItem));
}