You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中解决express-validator自定义验证函数参数隐式any问题

解决express-validator自定义验证器参数隐式any的问题

要给自定义验证器的value参数指定string类型,有两种简洁可靠的方式:

方式一:直接显式声明参数类型

直接在参数上添加string类型注解,同时用satisfies确保验证器符合express-validator的类型约束,避免类型不匹配:

import { ExpressValidator, CustomValidator } from 'express-validator';

const { body } = new ExpressValidator({
  isPostID: async (value: string) => {
    // 编写Post ID格式验证逻辑,示例:检查是否符合短ID格式
    const isValidFormat = /^[a-z0-9-]{10,20}$/.test(value);
    if (!isValidFormat) {
      throw new Error('Post ID格式无效');
    }
    return true;
  },
} satisfies Record<string, CustomValidator<string>>);

方式二:通过泛型定义自定义验证器类型

提前定义好自定义验证器的类型结构,传给ExpressValidator泛型,让TypeScript全程提供精准的类型检查:

import { ExpressValidator } from 'express-validator';

// 自定义验证器的类型定义
type CustomValidators = {
  isPostID: (value: string) => Promise<boolean>;
};

const { body } = new ExpressValidator<CustomValidators>({
  isPostID: async (value: string) => {
    // 验证逻辑示例
    return /^[a-z0-9-]{10,20}$/.test(value);
  },
});

补充说明

因为你明确知道传入的值始终为string,直接声明value: string完全安全,无需使用any。两种方式都能解决VS Code的隐式any提示,同时让TypeScript在编写验证逻辑时提供更准确的类型提示。

内容的提问来源于stack exchange,提问作者Pinocchio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 09:23:13