当我试图破坏以下函数的返回类型时:
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
分解为label
和confidence
,并且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希望确保此错误不会在运行时发生。因此,编译时的错误