Jesús Fuentes
Jesús Fuentes

Reputation: 919

Overriding a method in an extended class

I have the following typings:

export class CallBuilder<T extends Record> {
    constructor(serverUrl: string)
    call(): Promise<CollectionPage<T>>;
    cursor(cursor: string): this;
    limit(limit: number): this;
    order(direction: 'asc' | 'desc'): this;
    stream(options?: { onmessage?: (record: T) => void, onerror?: (error: Error) => void }): () => void;
}

export interface CollectionPage<T extends Record> {
    records: T[];
    next: () => Promise<CollectionPage<T>>;
    prev: () => Promise<CollectionPage<T>>;
}

export interface Record {
    _links: {
        [key: string]: RecordLink
    };
}

And I want to override the call() method from CallBuilder in a different class to bassically have the same functionality, except for the call() return.

export class PagedCallBuilder<T extends Record> extends CallBuilder<T> {
    call(): Promise<T>;
}

The call() line is giving the following error:

Property 'call' in type 'PagedCallBuilder' is not assignable to the same property in base type 'CallBuilder'. Type '() => Promise' is not assignable to type '() => Promise>'. Type 'Promise' is not assignable to type 'Promise>'. Type 'T' is not assignable to type 'CollectionPage'. Type 'Record' is not assignable to type 'CollectionPage'. Property 'records' is missing in type 'Record'.

How should I do this?

Upvotes: 1

Views: 587

Answers (1)

Matt McCutchen
Matt McCutchen

Reputation: 30919

The point of subclassing is that an object of the subclass is compatible with the interface of the superclass, so you can't change method return types arbitrarily. Instead, consider writing a common superclass that has all the functionality except the call method and writing two separate subclasses that each define the call method with a different return type.

Upvotes: 1

Related Questions