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

TypeScript函数组件可选属性访问及索引报错求解

解决TypeScript函数组件中的可选属性与索引错误

嘿,我来帮你搞定这两个TypeScript报错!先梳理下问题根源:虽然你给Button设置了defaultProps,但TypeScript的类型系统默认不会自动把defaultProps的默认值合并到组件的props类型推断里,所以props.size仍然被判定为可能是undefined,这就导致了两个错误:

  1. 访问props.size时的“property can't be undefined”错误
  2. 用props.size作为sizes对象的索引时,“undefined can't be an index”错误

下面给你几个实用的解决办法,结合你的代码修改:

方法1:在函数参数中直接设置默认值(最推荐)

直接在组件的参数解构时给size设置默认值,这样TypeScript就能明确知道size永远不会是undefined,同时还能简化代码:

import * as React from "react";

interface ButtonProps {
  /** Button label size*/
  size?: "small" | "normal" | "large";
  /** The content of the button */
  children: string;
};

const sizes = { small: "12px", normal: "18px", large: "24px" };

/**
 * A Button element
 */
export const Button: React.FC<ButtonProps> = ({ size = "normal", children }) => {
  // 这里size已经被默认值兜底,不会是undefined
  const targetFontSize = sizes[size];
  // 注意:之前你写错了,应该用targetFontSize而不是props.size作为fontSize的值
  const styles = { fontSize: targetFontSize };
  return <button style={styles}>{children}</button>;
};

// 现在defaultProps可以不用写了,保留也没问题
Button.defaultProps = { size: "normal" };
export default Button;

方法2:用空值合并运算符处理undefined情况

如果不想修改参数结构,可以用??空值合并运算符,在props.size为undefined时兜底到默认值:

export const Button: React.FC<ButtonProps> = (props) => {
  // 当props.size是undefined时,用"normal"作为索引
  const targetFontSize = sizes[props.size ?? "normal"];
  const styles = { fontSize: targetFontSize };
  return <button style={styles}>{props.children}</button>;
};

方法3:使用可选链+条件判断(兼容旧版TS)

如果你用的TypeScript版本不支持??,可以用可选链和三元表达式:

export const Button: React.FC<ButtonProps> = (props) => {
  const targetFontSize = props.size ? sizes[props.size] : sizes["normal"];
  const styles = { fontSize: targetFontSize };
  return <button style={styles}>{props.children}</button>;
};

另外要提醒你:原来代码里的const styles = { fontSize: props.size };是错误的,因为props.size是"small"/"normal"/"large"这些字符串,而fontSize需要的是像"12px"这样的有效CSS尺寸值,所以必须用targetFontSize来赋值哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:54:59