
[英]Typescript Object is possibly null even inside an if statement checking that the object is not null
[英]Object is possibly undefined, even with null checks
我正在使用 Typescript 4.0.5 并且得到了一个不可抑制的
Object is possibly undefined
错误
我有一个包含用户上传的 .csv 文件的本地状态
const [currentLine, setCurrentLine] = useState<File>();
我的 useEffect 监视文件更改并解析 csv
useEffect(
() => {
currentFile !== null && currentFile !== undefined && currentFile.type === 'text/csv'
? Papa.parse(currentFile, {
complete: (csv: File) => setParsedFile(csv)
})
: null;
},
[currentFile]
);
即使使用 null 和 undefined 检查,我仍然收到错误
Object is possibly 'undefined'.ts(2532)
我尝试将 null/undefined 检查包装在 if 语句中并得到相同的错误,并且还尝试使用可选链接
currentFile?.type === 'text/csv'
后一个选项似乎将 currentFile 强制为 never 并告诉我 .type 不存在于 never...
我在这里做错了什么吗? 我们有一个相当混乱的 package.json,我想知道是否需要更新某些工具,因为我在这里看不到任何错误的原因。 对于 linting 我在 eslint 7.13.0 上,使用 eslint-config-prettier 6.15 进行配置。
或许
const [currentFile, setCurrentFile] = useState<File>();
useEffect(() => {
if (currentFile && currentFile.type === 'text/csv')
Papa.parse(currentFile, {
complete: (csv: File) => setParsedFile(csv)
});
},
[currentFile]
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.