Typescript generic abstract class - Why doesn't this abstract method inherit the class type?

Viewed 153

I come from a background in C# and I'm currently trying to get my head around Typescript. I've run in to the following issue while creating a generic abtract class in Typescript, and I'm not sure if it's a problem with my implementation, or a limitation of the language:

Given the following abstract class, and class extending it:

abstract class Filter<T> {
    value T;
    abstract apply<T>(items: T[]): T[];
}

class StringFilter extends Filter<string> {
    apply(items: string[]) {
        return items.filter(i => this.value === i);
    }
}

I get the following error:

Property 'apply' in type 'StringFilter' is not assignable to the same property in base type 'Filter<string>'.
Type '(items: string[]) => string[]' is not assignable to type '<T>(items: T[]) => T[]'.

In C# I would have expected the apply method to share the same generic type as the class, but in Typescript this doesn't seem to be the case.

How can I make sure that a type of Filter<string> has an apply method of type (items: string[]) => string[]?

2 Answers

You need to remove the <T> from the abstract apply method.

How can I make sure that a type of Filter has an apply method of type (items: string[]) => string[]?

Well, you're already doing that. The definition of the abstract method "apply" is already ensuring your request. Setting the abstract class as generic, all the methods/props defined will inherit the T specification in the concrete class.

You don't need to provide the generic parameter to apply. The following modification of your code compiles without issues.

abstract class Filter<T> {
    value: T;
    abstract apply(items: T[]): T[];
}

class StringFilter extends Filter<string> {
    apply(items: string[]) {
        return items.filter(i => this.value === i);
    }
}
Related