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

为什么React+TypeScript中对props做函数参数解构时需要传入对象?

问题原因

你定义的genKeyId函数要求接收1个参数,参数类型为GenKeyIdProps对象,你虽然给length属性设置了默认值,但是没有给整个参数对象设置默认值,所以调用时必须传入至少一个空对象,否则TS会判定你漏传了必填参数。

你当前的函数签名const genKeyId = ({ length = 5 }: GenKeyIdProps) => ...的实际含义是:

  • 第一个参数是GenKeyIdProps类型的对象,该参数为必填项
  • 仅当传入的对象中length属性不存在/为undefined时,默认取值为5

如果想要不传参数也能正常调用,你需要给整个参数对象设置默认值为空对象,修改后的函数签名如下:

export const genKeyId = ({ length = 5 }: GenKeyIdProps = {}) => Math.random().toString(36).substr(2, length);

新增的= {}就是给整个参数对象设置默认值为{},当你不传参数调用genKeyId()时,TS会自动将该空对象作为入参,解构时length不存在就会取默认值5,不会再抛出参数缺失的报错。

额外优化建议
  • 你注释里的${lenght}拼写有误,正确拼写为length,且JSDoc注释内不需要使用模板字符串语法,直接描述即可
  • 目前substr方法已被标记为弃用,推荐改用substring方法,修改后的完整代码如下:
interface GenKeyIdProps {
  length?: number;
}

/**
 * Generate a random id (mainly for use with rendering lists of components.
 * genKeyId convert Math.random to base 36 (numbers + letters), and grab the first 5 characters after the decimal by default.
 * @param length (optional) specify how many characters the id should be. default is 5.
 * @returns a string with number and letters of specified length.
 */
export const genKeyId = ({ length = 5 }: GenKeyIdProps = {}) => Math.random().toString(36).substring(2, 2 + length);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:36:01