TypeScript未校验React组件prop传入的函数参数不足,如何开启严格校验
问题原因
TypeScript默认允许函数入参个数少于目标类型定义的个数,这是官方设计的兼容性行为:JavaScript运行时本身允许给函数传入多于定义数量的参数,多余参数会被函数自动忽略,因此TypeScript认为「参数更少、对应位置参数类型匹配的函数」是兼容目标类型的,默认不会抛出错误。
解决方案
方案1:自定义严格函数类型(推荐,局部生效不影响全局代码)
你可以定义一个工具类型,强制要求传入的回调参数个数、参数类型完全匹配定义,不会兼容少参数的场景:
// 定义严格函数工具类型:入参个数、类型、返回值完全匹配要求 type StrictFunction<Args extends any[], Return> = (...args: Args) => Return & { length: Args['length'] };
将你的组件props中onSearch的类型替换为上述工具类型即可:
import type { FC, FormEvent, useRef } from 'react'; // 替换原有onSearch类型定义 const BirthdaySearch: FC<{ onSearch: StrictFunction<[year: string, month: string], void> }> = (props) => { // 原有组件逻辑不变 const monthInputRef = useRef<HTMLInputElement>(null); const dayInputRef = useRef<HTMLInputElement>(null); const submitHandler = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); // 注:原代码此处存在笔误,selectedYear未定义,按逻辑应为selectedDay const selectedDay = dayInputRef!.current!.value; const selectedMonth = monthInputRef!.current!.value; props.onSearch(selectedDay, selectedMonth); }; return ( <form onSubmit={submitHandler}> <div> <div> <label htmlFor="month">Month</label> <input name="month" id="month" ref={monthInputRef} /> </div> <div> {/* 注:原代码此处label的htmlFor属性笔误为month,已修正为day */} <label htmlFor="day">Day</label> <input name="day" id="day" ref={dayInputRef} /> </div> </div> <button>Find People By Birthday</button> </form> ); }; export default BirthdaySearch;
修改后父组件传入0参数的findBdHandler时,TypeScript会直接抛出类型不兼容的错误,只有参数个数、类型完全匹配的函数才能通过校验。
方案2:ESLint全局规则校验
如果需要全局生效这类校验,可以安装@typescript-eslint/eslint-plugin,开启@typescript-eslint/no-mismatched-function-arity规则,该规则会全局检查所有函数赋值场景的参数个数是否匹配。
内容的提问来源于stack exchange,提问作者chocojunkie
相关产品推荐
相关产品推荐

