Marc Rasmussen
Marc Rasmussen

Reputation: 20555

Typescript returns interface of type instead of type

So i have the following class:

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));
    };
}

where IHttpResponse look like this:

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

Now i wish to use this class so i have created the following:

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) {

    }
}

However at the this.ProcessResponse i get the following error:

TS2345: Argument of type 'IHttpResponse' is not assignable to parameter of type 'IContentData'.   Type 'IHttpResponse' is missing the following properties from type 'IContentData': id, htmlTag, importJSComponent, componentData

Can anyone tell me what ive done wrong?

Upvotes: 0

Views: 63

Answers (1)

Todd Skelton
Todd Skelton

Reputation: 7239

const response is of the type IHttpResponse<IContentData>

You need to pass response.parsedBody to your method.

    public async GetContent(url: string) {
        const response = await super.get<IContentData>(url, {});

        response?.parsedBody && this.ProcessResponse(response.parsedBody);

    }

    private ProcessResponse(ContentData: IContentData) {

    }

Upvotes: 1

Related Questions