LoginSignup
1
0

【TypeScript】yupで型付けする方法

Posted at

yupで型を付ける方法をご紹介します。スキーマに型を付けることで、バリデーションが効かないなどのミスを防ぐことができるので、yupを使用している人は試してみてください。

環境

yupのバージョンは1.3.3で動作確認しています。

結論

ObjectSchemaで作成したスキーマに型を付ける

使用例

例1

name, ageは必須の場合

import * as yup from 'yup';
import type { ObjectSchema } from 'yup';

type User = {
  name: string;
  age: number;
};

const UserSchema: ObjectSchema<User> = yup.object().shape({
  name: yup.string().required(),
  age: yup.number().required(),
});

例2

nameは必須、ageは必須でない場合

ageを省略すると型エラーとなるため、必須でない場合でもyup.number().defined()のようにスキーマを定義します。

import * as yup from 'yup';
import type { ObjectSchema } from 'yup';

type User = {
  name: string;
  age: number;
};

const UserSchema: ObjectSchema<User> = yup.object().shape({
  name: yup.string().required(),
  age: yup.number().defined(),
});

例3

name, ageは必須、addressage20以上で必須の場合

whenの後(前でも可能)にshapeでスキーマを定義します。

import * as yup from 'yup';
import type { ObjectSchema } from 'yup';

type User = {
  name: string;
  age: number;
  address: {
    prefecture: string;
    city: string;
  };
};

const UserSchema: ObjectSchema<User> = yup.object().shape({
  name: yup.string().required(),
  age: yup.number().required(),
  address: yup
    .object()
    .when('age', {
      is: (age: User['age']) => age >= 20,
      then: (schema) =>
        schema.shape({
          prefecture: yup.string().required(),
          city: yup.string().required(),
        }),
    })
    .shape({
      prefecture: yup.string().defined(),
      city: yup.string().defined(),
    }),
});

まとめ

yupに型を付ける方法をご紹介しました。必須でない場合でもdefinedでスキーマを定義しないと型エラーとなるため注意が必要です。

最後に

GoQSystemでは一緒に働いてくれる仲間を募集中です!

ご興味がある方は以下リンクよりご確認ください。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0