首页 > 解决方案 > 类型 '{ 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'.

标签: typescriptreact-nativeeslint

解决方案


您的函数的结果是{label: string, confidence: string}or undefined。哪一个在编译时是未知的。但是你不能解构undefinedlabel 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 想要确保,这个错误不会在运行时发生。因此,编译时的错误


推荐阅读