Typescript和Express Validator自定义验证类型

时间:2019-04-20 11:27:55

标签: typescript express express-validator

使用快速验证器的自定义方法时出现错误

Argument of type '(userDoc: User | null) => Promise<never> | undefined' is not assignable to parameter of type '(value: User | null) => PromiseLike<never>'.
  Type 'Promise<never> | undefined' is not assignable to type 'PromiseLike<never>'.
    Type 'undefined' is not assignable to type 'PromiseLike<never>'.

import express from 'express';
import { body } from 'express-validator/check'
import User from '../models/User';

import { login, signUp } from '../controllers/auth';
const router = express.Router();

router.post(
  '/sign-up',
  [
    body('username', 'User Name should be atlest 4 characters long')
      .isLength({ min: 4 })
      .isString()
      .trim()
    .custom((username: string, { req }) => {
      return User.findOne({ username }).then(userDoc => {
        if (userDoc) {
          return Promise.reject('User Name is already taken');
        }
      });
    })
  ],
  signUp,
);

1 个答案:

答案 0 :(得分:1)

实现User.findOne的方式返回一个Promise。这就是为什么您使用Promise.reject来引发错误的原因。因此,如果验证成功,您也必须返回Promise对象。

if (userDoc) {
    return Promise.reject('User Name is already taken');
}
return Promise.resolve()