首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型'{ label: string;confidence: string;}| undefined‘上不存在属性'confidence’

类型'{ label: string;confidence: string;}| undefined‘上不存在属性'confidence’
EN

Stack Overflow用户
提问于 2021-07-20 03:34:12
回答 1查看 32关注 0票数 0

当我试图解构以下函数的返回类型时:

代码语言:javascript
复制
const coreml = async (
  pathToImage: string,
): Promise<{label: string; confidence: string} | undefined> => {
  //body
};

因此:

代码语言:javascript
复制
const {label, confidence} = await coreml(/*path to image*/);

我得到了

代码语言:javascript
复制
'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'.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-20 03:45:29

函数的结果是{label: string, confidence: string}undefined。哪一个在编译时是未知的。但是您不能将undefined解构为labelconfidence,而typescript希望确保类型安全。这样就产生了错误。

原则上,解构的工作方式如下:

代码语言:javascript
复制
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希望确保,此错误不会在运行时发生。因此,编译时的错误

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68446076

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档