【问题标题】:Object is possibly 'undefined'.ts(2532) after do check for object [duplicate]检查对象后,对象可能是“未定义”.ts(2532) [重复]
【发布时间】:2022-01-04 17:21:54
【问题描述】:

我收到此错误Object is possibly 'undefined'.ts(2532)

这是我的配置

export interface IDataColumns {
  name: string;
  label: string;
  display: string;
  empty: boolean;
  filter: boolean;
  sort: boolean;
  print: boolean;
  searchable: boolean;
  download: boolean;
  viewColumns: boolean;
  sortCompare?: null;
  sortThirdClickReset: boolean;
  sortDescFirst: boolean;
  filterType?: string | null;
  setCellProps?: () => {
    style: SxProps<Theme>;
  };
}

这是我的代码,我在调用函数之前正在检查setCellProps,但我收到此错误Object is possibly 'undefined'.ts(2532) 有人知道如何解决这个问题吗?

    const styles = () => {
        if (props.columns[index].setCellProps) {
            const style = props.columns[index].setCellProps();
         return style.style;
        }
      return {};
    };

【问题讨论】:

  • ms/TS#10530 和链接问题的答案。当 idx 是一个变量时,TypeScript 无法缩小 arr[idx] 的类型。一种解决方法是将其复制到自己的变量中,例如const v = props.columns[index],然后是if (v.setCellProps) { v.setCellProps(); }。当然,此时您可以执行props.columns[index].setCellProps?.().style ?? {} 之类的操作。你的代码不是真正的minimal reproducible example,所以我无法检查它是否有效。

标签: typescript


【解决方案1】:

如果您的示例中没有行号,我会怀疑两个问题之一。

   const styles = () => {
        if (props.columns[index].setCellProps) {
            const style = props.columns[index].setCellProps();
            //                               ^ Typescript isn't tracking that you just accessed props.columns[index] in the if statement above
         return style.style;
            // or setCellProps can sometimes return null, although the interface you posted seem to suggest this isn't the case.
        }
      return {};
    };

可能的解决方案

   const styles = () => {
        const setCellProps = props.columns[index].setCellProps
        if (setCellProps) {
            const style = setCellProps();
            if (style) {
               return style.style;
            }
        }
      return {};
    };

【讨论】:

    猜你喜欢
    • 2019-09-16
    • 2021-06-03
    • 1970-01-01
    • 2020-02-21
    • 2021-02-03
    • 2021-01-19
    • 2021-08-09
    • 2019-11-16
    • 2021-10-27
    相关资源
    最近更新 更多