如何强制TypeScript函数使用接口中的所有输入参数?
确保TypeScript函数使用指定输入参数的方案
方案1:启用TypeScript全局未使用参数检查
开启--noUnusedParameters编译选项(在tsconfig.json的compilerOptions中配置),TypeScript会对所有未使用的函数参数抛出错误,包括可选的select。
示例tsconfig.json配置:
{ "compilerOptions": { "noUnusedParameters": true } }
效果:如果findUser函数中未访问params.select,TypeScript会直接报错。
局限性:该选项全局生效,会检查所有函数的未使用参数,可能干扰其他无需强制检查的场景。
方案2:用高阶函数强制处理指定参数
通过封装高阶函数,强制业务函数必须接收并处理select参数,从类型层面确保参数被使用。
示例代码:
// 共享查询参数 interface FindQueryParams { select?: string; } // 用户查询参数 interface FindUserParams extends FindQueryParams { userId: number; } // 创建查询函数的高阶工具 function createFindQuery<T extends FindQueryParams>( handler: (params: T, select: T['select']) => unknown ) { return (params: T) => { // 强制提取select并传入handler,确保业务逻辑必须处理它 return handler(params, params.select); }; } // 定义findUser时必须处理select参数 const findUser = createFindQuery((params: FindUserParams, select) => { // 必须使用select,否则TypeScript会提示未使用参数 const queryColumns = select ?? '*'; const user = {}; // 模拟查询逻辑 return user; });
效果:业务函数必须接收select作为单独参数,若未使用则触发TypeScript错误,同时保留原有参数结构的调用方式(findUser({ userId: 1, select: 'name' }))。
方案3:ESLint规则针对性检查
使用@typescript-eslint/no-unused-vars规则,通过注释或配置强制检查特定参数的使用情况。
示例代码:
interface FindQueryParams { select?: string; } interface FindUserParams extends FindQueryParams { userId: number; } // 强制检查params中的select参数是否被使用 // eslint-disable-next-line @typescript-eslint/no-unused-vars function findUser(params: FindUserParams){ // 必须解构或访问params.select,否则ESLint报错 const { userId, select } = params; const query = `SELECT ${select || '*'} FROM users WHERE id = ${userId}`; const user = {}; return user; }
效果:可针对单个函数或参数做精准检查,无需全局修改TypeScript编译选项。
内容的提问来源于stack exchange,提问作者Ege Cavusoglu
相关产品推荐
相关产品推荐

