【发布时间】: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