属性 'confidence' 不存在于类型 '{ label: string;置信度:字符串; } |不明确的'

Property 'confidence' does not exist on type '{ label: string; confidence: string; } | undefined'

当我尝试解构以下函数的 return 类型时:

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}undefined。哪一个在编译时是未知的。但是你不能将 undefined 解构为 labelconfidence 并且打字稿想要确保类型安全。因此错误。

原则上解构工作如下:

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 想要确保,这个错误不会在运行时发生。因此,编译时的错误