0

I have the following interfaces and classes in TypeScript:

export interface PageInterface<T> {
    count: number;
    previous: string;
    next: string;
    results: T[];
}

export class Page<T> implements PageInterface<T> {}

----------------------------------------------------------

export interface AdapterInterface<T> {
    adapt(item: any): T;
}

And I need to implement PageAdapter<Page<T>>.

Is it possible? I've tried the following but ended up with errors (Type 'Page' si not generic):

export class PageAdapter<Page> implements AdapterInterface<Page> {
    adapt(item: any): Page<T> {
        return new Page<T>(item['count'], item['previous'], item['next'], item['results']);
    }
}

If I put Page<T> instead of Page in the first line, it doesn't work at all.

How can i implement this?

Many thanks,

1 Answer 1

1

I presume that you're looking for something like this:

export class PageAdapter<T> implements AdapterInterface<Page<T>> {
    adapt(item: any): Page<T> {
        return new Page<T>(item['count'], item['previous'], item['next'], item['results']);
    }
}

So, for example, a PageAdapter<string> can be used as an AdapterInterface<Page<string>>. If you really need the generic type parameter to be a Page-like type, you can write something like this:

export class PageAdapter2<P extends Page<any>> implements AdapterInterface<P> {
    adapt(item: any): P {
        return new Page(item['count'], item['previous'], item['next'], item['results']) as P;
    }
}

Here, a PageAdapter<Page<string>> can be used as an AdapterInterface<Page<string>>. The typings for this version are not as clean, however, and require type assertions to implement.

Hope that helps; good luck!

Playground link to code

Sign up to request clarification or add additional context in comments.

1 Comment

The first piece of code accomplished what i needed. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.