Typescript返回类型的接口,而不是类型



所以我有以下类:

export abstract class SuperIO {
async http<T>(
request: RequestInfo
): Promise<IHttpResponse<T>> {
const response: IHttpResponse<T> = await fetch(
request
);
try {
response.parsedBody = await response.json();
} catch (ex) {
}
if (!response.ok) {
throw new Error(response.statusText);
}
return response;
}
async get<T>(
path: string,
body: any,
args: RequestInit = {method: "get", body: JSON.stringify(body)}
): Promise<IHttpResponse<T>> {
return await this.http<T>(new Request(path, args));
};
}

其中IHttpResponse如下所示:

interface IHttpResponse<T> extends Response{
parsedBody?: T;
}

现在我希望使用这个类,所以我创建了以下内容:

import {SuperIO} from "../Framework/SuperIO";

export interface IContentData {
id: number;
url: string;
htmlTag: string;
importJSComponent: string;
componentData: string
}
export class ContentIOService extends SuperIO {
public async GetContent(url: string) {
const response = await super.get<IContentData>(url, {});
this.ProcessResponse(response);
}
private ProcessResponse(ContentData: IContentData) {
}
}

然而,在this.ProcessResponse上,我得到了以下错误:

TS2345:类型为"IHttpResponse"的参数不可分配给类型为"IContentData"的参数。类型"IHttpResponse"缺少类型"IContentData"中的以下属性:id、htmlTag、importJSComponent、componentData

有人能告诉我我做错了什么吗?

const response属于IHttpResponse<IContentData>类型

您需要将response.parsedBody传递给您的方法。

public async GetContent(url: string) {
const response = await super.get<IContentData>(url, {});
response?.parsedBody && this.ProcessResponse(response.parsedBody);
}
private ProcessResponse(ContentData: IContentData) {
}

最新更新