typescript - 类型 '{ label: string; 上不存在属性 'confidence' 信心:字符串;} | 不明确的'
问题描述
当我尝试解构以下函数的返回类型时:
const coreml = async (
pathToImage: string,
): Promise<{label: string; confidence: string} | undefined> => {
//body
};
像这样:
const {label, confidence} = await coreml(/*path to image*/);
我明白了
'confidence' is assigned a value but never used.eslint@typescript-eslint/no-unused-vars
Property 'confidence' does not exist on type '{ label: string; confidence: string; } | undefined'.
解决方案
您的函数的结果是{label: string, confidence: string}
or undefined
。哪一个在编译时是未知的。但是你不能解构undefined
为label
andconfidence
并且 typescript 想要确保类型安全。因此错误。
原则上,解构工作如下:
const temp = await coreml();
//temp is now either {"label": "foo", "confidence": "bar"} or undefined
//but the next statements will throw an error, if temp is undefined
const label = temp.label;
const confidence = temp.confidence;
Typescript 想要确保,这个错误不会在运行时发生。因此,编译时的错误
推荐阅读
- wordpress - Wordpress - 管理员批准后如何自动登录用户?
- python - pymysql SELECT * 仅在实例化新连接后检测外部所做的更改
- javascript - 我应该选择代码重复还是与 api 服务合并 - JS
- python - Discord py 获取输入
- mysql - MariaDB(或 MySQL)是否需要 SSL 证书以确保安全
- postgresql - Postgres - 查询数组数组中的特定值
- python - 从 pcap 会话中提取 RTP 流
- reactjs - TypeError: Object(...) is not a function Redux Store
- javascript - 输入变量可见,但在 Ajax 、 $each 和 Div 克隆过程之后不可访问
- html - TAILWIND CSS [Unknown at rule @tailwindcss(unknownAtRules)] 解决此错误