generated at
Yupで独自のmethodを追加する
from Yup

これに対するTypeScriptの対応
例.ts
yup.addMethod<yup.StringSchema>(yup.string, 'emailMax', function () { return this.max( validLength.EMAIL_MAX_LENGTH, `${validLength.EMAIL_MAX_LENGTH}文字以内で入力してください` ); });
<yup.StringSchema> を教えてあげないと this の内容が正しくならない
これを利用すると型エラーになる
使用側.ts
yup.string().katakana();
こうする
ts
declare module 'yup' { interface StringSchema { emailMax(this: StringSchema): StringSchema; usernameMax(this: StringSchema): StringSchema; onlyAlphaNumAndDotUnderbar(this: StringSchema): StringSchema; notLastPeriod(this: StringSchema): StringSchema; } }
with this.test
ts
yup.addMethod<yup.StringSchema>(yup.string, 'phoneNumber', function () { return this.test( 'phoneNumber', '電話番号の形式が正しくありません', function (value) { // value :: string|null if (value == null) return true; const pn = new PhoneNumber(value, 'JP'); return pn.isValid(); } ); });
this で使えるmethodはなに?


例えば「最大の長さ」を使いまわししてaddMethodする
ts
const v = { usernameMax: 50, // ユーザ名の最大文字数 emailMax: 100 }; (Object.keys(v) as (keyof typeof v)[]).map(key => { yup.addMethod<yup.StringSchema>(yup.string, key, function () { return this.max(v[key], `${v[key]}文字以内で入力してください`); }); });
${v[key]}文字以内で入力してください というエラーメッセージを共通して使いたいので、こういう関数を定義しておくと、あとは上の辞書に関数名と数値を指定するだけで済む