본문으로 바로가기

Type validation 뭐 써볼까?

category software engineering/frontend 2023. 9. 21. 22:51

소개

JavaScript에서 데이터 유효성 검사를 처리할 때 개발자는 종종 올바른 라이브러리를 선택해야 하는 어려움에 직면합니다. 검증에 널리 사용되는 세 가지 옵션은 Yup, Zod 및 Joi입니다. 이 기사에서는 각 라이브러리의 기능, 코드 조각을 자세히 알아보고 장점과 단점을 비교하여 프로젝트에 대한 정보에 근거한 결정을 내리는 데 도움을 드립니다.

타입스크립트의 역할

  • 타입스크립트 코드에서의 타입에러는 "컴파일" 과정에서만 발생
  • 실제로 런타임에는 타입스크립트는 아무것도 역할을 하지 못한다

네: 우아하고 간편해요

그렇습니다. 데이터 스키마 유효성 검사를 위한 간단하고 우아한 라이브러리입니다. 선언적 API를 제공하므로 유효성 검사 규칙을 쉽게 읽고 이해할 수 있습니다. 가벼운 특성으로 인해 성능이 중요한 소규모 프로젝트나 시나리오에 적합합니다.

사용 예:

!https://res.cloudinary.com/practicaldev/image/fetch/s--SejIfOS9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uht4odsb5i6fr7l6h8s7.png

장점:

  • 읽기 쉬운 유효성 검사 규칙을 위한 선언적 구문입니다.
  • 중소 규모 프로젝트에 적합하고 가볍고 빠릅니다.
  • 좋은 커뮤니티 지원과 적극적으로 유지 관리됩니다.

단점:

  • 보다 광범위한 프로젝트를 위한 복잡한 검증 기능이 부족합니다.
  • 다른 도서관에 비해 생태계가 제한적입니다.

Zod: 강력하고 유형이 안전함

Zod는 TypeScript의 유형 시스템을 활용하는 능력이 뛰어난 강력한 검증 라이브러리입니다. TypeScript를 사용하는 경우 Zod의 유형 추론은 유효성 검사 코드가 유형에 안전한지 확인하여 데이터 처리에 대한 추가적인 확신을 제공합니다.

사용 예:

!https://res.cloudinary.com/practicaldev/image/fetch/s--Z2K4ESD4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hew75kcczwweo6oaa3lc.png

장점:

  • 유형 안전 검증을 위한 강력한 TypeScript 지원.
  • 강력한 검증 기능과 풍부한 검증 API.
  • 뛰어난 오류 메시지 및 오류 처리.

단점:

  • TypeScript에 익숙하지 않은 개발자를 위한 학습 곡선.
  • TypeScript를 사용하지 않는 프로젝트에 오버헤드가 추가될 수 있습니다.

Joi: 풍부한 기능과 실전 테스트를 거침

Joi는 Node.js 애플리케이션에서 자주 사용되는 성숙하고 기능이 풍부한 검증 라이브러리입니다. 광범위한 검증 규칙과 사용자 정의 옵션을 제공하므로 복잡한 검증 시나리오에 적합합니다.

사용 예:

!https://res.cloudinary.com/practicaldev/image/fetch/s--uu2iUtW5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yr246x2keh2bhbzt6vcv.png

장점:

  • Node.js 생태계에서 전투 테스트를 거쳐 널리 사용됩니다.
  • 광범위한 검증 규칙 및 옵션 세트.
  • 강력한 오류 처리 및 사용자 정의 기능.

단점:

  • 규모가 커지고 소규모 프로젝트에 약간의 오버헤드를 추가할 수 있습니다.
  • TypeScript 프로젝트에서 유형 안전을 위해 더 많은 노력이 필요할 수 있습니다.

Jo

Doesn't support static type inference 😕

Yup

Yup is a full-featured library that was implemented first in vanilla JS, and later rewritten in TypeScript.

  • Supports casting and transforms
  • All object fields are optional by default
  • Missing promise schemas
  • Missing function schemas
  • Missing union & intersection schemas

io-ts

io-ts is an excellent library by gcanti. The API of io-ts heavily inspired the design of Zod.

In our experience, io-ts prioritizes functional programming purity over developer experience in many cases. This is a valid and admirable design goal, but it makes io-ts particularly hard to integrate into an existing codebase with a more procedural or object-oriented bias. For instance, consider how to define an object with optional properties in io-ts:

import * as t from "io-ts";

const A = t.type({
  foo: t.string,
});

const B = t.partial({
  bar: t.number,
});

const C = t.intersection([A, B]);

type C = t.TypeOf<typeof C>;
// returns { foo: string; bar?: number | undefined }

Consider the equivalent in Zod:

const C = z.object({
  foo: z.string(),
  bar: z.number().optional(),
});

type C = z.infer<typeof C>;
// returns { foo: string; bar?: number | undefined }
  • Supports codecs with serialization & deserialization transforms
  • Supports branded types
  • Supports advanced functional programming, higher-kinded types, fp-ts compatibility
  • Missing object methods: (pick, omit, partial, deepPartial, merge, extend)
  • Missing nonempty arrays with proper typing ([T, ...T[]])
  • Missing promise schemas
  • Missing function schemas

Runtypes

Good type inference support.

  • Supports "pattern matching": computed properties that distribute over unions
  • Missing object methods: (deepPartial, merge)
  • Missing nonempty arrays with proper typing ([T, ...T[]])
  • Missing promise schemas
  • Missing error customization

Ow

Ow is focused on function input validation. It's a library that makes it easy to express complicated assert statements, but it doesn't let you parse untyped data. They support a much wider variety of types; Zod has a nearly one-to-one mapping with TypeScript's type system, whereas ow lets you validate several highly-specific types out of the box (e.g. int32Array , see full list in their README).

If you want to validate function inputs, use function schemas in Zod! It's a much simpler approach that lets you reuse a function type declaration without repeating yourself (namely, copy-pasting a bunch of ow assertions at the beginning of every function). Also Zod lets you validate your return types as well, so you can be sure there won't be any unexpected data passed downstream.

Valibot

유튜브에 많이 나오지만 대학생 1인 개발

  • Missing promise schemas
  • Missing function schemas
  • Missing union & intersection schemas

타입스크립트를 쓰는데도 유효성 검증이 필요할까?

 

결론

Yup, Zod, Joi 등 각 검증 라이브러리에는 고유한 장점과 사용 사례가 있습니다.

  • 네, 단순성과 가벼운 특성 덕분에 간단한 검증 요구에 탁월한 선택입니다.
  • Zod는 유형 안전성과 강력한 검증 기능을 활용하는 TypeScript 프로젝트를 위한 강력한 옵션입니다.
  • Joi는 광범위한 검증 규칙과 사용자 정의 옵션을 제공하는 보다 복잡한 시나리오를 위한 라이브러리입니다.

궁극적으로 선택은 프로젝트 요구 사항, TypeScript에 대한 친숙도, 데이터 검증에 필요한 복잡성 수준에 따라 달라집니다. 어떤 라이브러리를 선택하든 이러한 검증 도구는 의심할 여지없이 JavaScript 애플리케이션의 신뢰성과 정확성을 향상시킵니다. 즐거운 코딩하세요!

zod가 import 해서 사용하는 z 인스턴스에 모든 메서드를 다 읽어야 하는 문제가 있지만 타입 검증을 위한 라이브러리 답게 제공하는 기능이 많아서 선택하겠습니다.

  • Missing promise schemas
  • Missing function schemas
  • Missing union & intersection schemas

z.string() 이 걸리신다면 yup을, valibot은 1인 개발에 위에 기능들이 부족해서 개인적으로는 zod가 1순위, yup가 2순위로 마음에 드네요.

의견을 제안했고 zod로 결정

Yup vs. Zod vs. Joi: A Comprehensive Comparison of JavaScript Validation Libraries

'software engineering > frontend' 카테고리의 다른 글

처음 써보는 tailwindcss  (1) 2023.10.29
예측하지 못한 useCallback, react.memo 상황  (1) 2023.10.29
Monorepo 뭐 써볼까?  (0) 2023.09.21
Style, CSS 뭐 써볼까?  (0) 2023.09.21
QueryClient 뭐 써볼까?  (0) 2023.09.21