我有一个返回联合类型的函数:
export const getCarMakes = (year: number): Promise<IMakes |IErrorResponse> => {
return fetch(
'url', {
method: 'GET',
})
.then((res: Response) => res.json())
.then((data: IMakes | IErrorResponse) => data)
.catch((error: any) => {
throw new Error(error);
});
};
具有接口:
interface IMakes {
makes: string [];
}
interface IErrorResponse {
code: number;
msg: string;
}
目前VS代码抱怨
Property 'code' does not exist on type 'IMakes | IErrorResponse'.
Property 'code' does not exist on type 'IMakes'.
我想我错过了一些东西,因为我可以从API那里获得2个完全不同的响应,这可以是一个有效的响应,其中包含一组项目或错误消息。我该如何解决这个问题
答案 0 :(得分:1)
我以前曾经遇到过这个问题,我已通过在返回任何内容之前检查函数要返回的内容来解决它。
例如,使用此功能
interface Foo {
foo: string;
}
interface Bar {
bar: boolean;
}
async function fooBar(): Promise<Foo | Bar> {
try {
const response = await asyncFn();
return Promise.resolve({ foo: '' })
} catch (err) {
return Promise.reject({ bar: false });
}
}
此函数可以返回Foo
或Bar
,但是由于返回取决于try/catch
中发生的情况,因此TypeScript不会对两种情况都进行检查,但如果不通过,则不会另一个。
所以做的时候:
fooBar()
.then(console.log)
.catch(console.error);
TypeScript不会引发TypeError,因为函数的返回取决于逻辑,该逻辑使函数可以返回两个值。
这是我的意思TypeScript playground的示例实现。我几乎100%确信TypeScript仅在拥有strictFunctionTypes
选项的情况下抱怨这一点。
希望这很清楚。