Posted at

express-validatorでschemaを使う (Typescript + Express)

More than 1 year has passed since last update.

express-validatorでschemaを定義して使おうとしてハマったのでメモ。

(ハマったというよりドキュメントには詳しく書かれていなかった)

バージョン

express 4.16.3

typescript 2.8.1

express-validator 5.2.0

このコードをリファクタリングしようとしました。


app.ts


import {checkSchema} from 'express-validator/check'

router.get('/', checkSchema({
dep: {
in: ['query'],
errorMessage: 'dep is wrong',
optional: true
},
age: {
in: ['query'],
errorMessage: 'age is wrong',
isInt: true,
toInt: true
}
}), (req, res, next) => {

}



app.ts


import {checkSchema} from 'express-validator/check'

const schema = {
dep: {
in: ['query'],
errorMessage: 'dep is wrong',
optional: true
},
age: {
in: ['query'],
errorMessage: 'age is wrong',
isInt: true,
toInt: true
}
}
router.get('/', checkSchema(schema), (req, res, next) => {

}


tecコマンドの実行後、以下のようなエラーが…

app.ts: error TS2345: Argument of type '{ dep: { in: string[]; errorMessage: string; optional: boolean; }; age: { in: string[]; errorMess...' is not assignable to parameter of type 'Record<string, ValidationParamSchema>'.

Property 'dep' is incompatible with index signature.
Type '{ in: string[]; errorMessage: string; optional: boolean; }' is not assignable to type 'ValidationParamSchema'.
Types of property 'in' are incompatible.
Type 'string[]' is not assignable to type '"body" | "headers" | "params" | "query" | "cookies" | Location[]'.
Type 'string[]' is not assignable to type 'Location[]'.
Type 'string' is not assignable to type 'Location'.

Typescriptの恩恵を受けています…

これで解決


app.ts


import {checkSchema, ValidationSchema} from 'express-validator/check'

const schema: ValidationSchema = {
dep: {
in: ['query'],
errorMessage: 'dep is wrong',
optional: true
},
age: {
in: ['query'],
errorMessage: 'age is wrong',
isInt: true,
toInt: true
}
}
router.get('/', checkSchema(schema), (req, res, next) => {

}


documentに書いてほしいのですが、こういうのってpull requestすれば良いのでしょうか…(OSS初心者)