【发布时间】:2019-01-09 18:56:12
【问题描述】:
我有一个返回联合类型的函数:
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 个完全不同的响应,这些响应可以是带有项目数组的有效响应,也可以是带有消息的错误。我该如何解决这个问题
【问题讨论】:
-
这很好
export const getMakes = (year: number): Promise<IMakes | IErrorResponse> => Promise.resolve({ code: 0, msg:"" }),你能发布更多代码吗? -
你能展示你的函数的实现吗?
标签: javascript typescript