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

FlowJS报错:无法获取size.width,因size可能为undefined的修复求助

修复FlowJS中可选对象属性的访问错误

报错信息

Error ------------------------------------------------------------ src/Components/Button/Button.component.style.js:38:17

Cannot get size.width because property width is missing in undefined [1]. [incompatible-use]

 [1] 34|   size?: Option
     35| ): $Shape<CSSStyleDeclaration> =>
     36|   compose(baseStyle, {
     37|     backgroundColor: bgColor,
     38|     width: size.width,
     39|     padding: size.padding,
     40|     color: textColor
     41|   });

当前代码

样式函数

export const setStyleButton = (
  bgColor?: string,
  textColor?: string,
  size?: Option
): $Shape<CSSStyleDeclaration> =>
  compose(baseStyle, {
    backgroundColor: bgColor,
    width: size.width,
    padding: size.padding,
    color: textColor
  });

Flow类型定义

// @flow
export type Option = {|
  padding:string,
  width:string
|}

export type Options = {|
  [key:string] : Option
|}

export type Props = {|
  name: string,
  color?: string,
  textColor?: string,
  size?: Option,
  onPress: () => void,
  disabled: boolean,
|};

解决方案

问题根源是size为可选参数,当调用函数时未传入该参数,size会是undefined,直接访问size.width会触发Flow的类型检查错误。以下是三种修复方式:

1. 给size参数设置默认值

给size指定符合Option类型的默认值,确保它永远不会是undefined:

export const setStyleButton = (
  bgColor?: string,
  textColor?: string,
  size: Option = { padding: '0', width: 'auto' }
): $Shape<CSSStyleDeclaration> =>
  compose(baseStyle, {
    backgroundColor: bgColor,
    width: size.width,
    padding: size.padding,
    color: textColor
  });

2. 使用可选链操作符

Flow支持ES6+的可选链?.,当size为undefined时,size?.width会返回undefined,不会触发类型错误:

export const setStyleButton = (
  bgColor?: string,
  textColor?: string,
  size?: Option
): $Shape<CSSStyleDeclaration> =>
  compose(baseStyle, {
    backgroundColor: bgColor,
    width: size?.width,
    padding: size?.padding,
    color: textColor
  });

3. 条件判断后访问属性

通过显式的条件判断确保size存在后,再访问其属性:

export const setStyleButton = (
  bgColor?: string,
  textColor?: string,
  size?: Option
): $Shape<CSSStyleDeclaration> => {
  const styleOverrides = {
    backgroundColor: bgColor,
    color: textColor
  };
  
  if (size) {
    styleOverrides.width = size.width;
    styleOverrides.padding = size.padding;
  }
  
  return compose(baseStyle, styleOverrides);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:05:23