TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Suggestion: Interface extend generic type

Open andreasbotsikas opened this issue 11 years ago • 37 comments

Hi all,

I was hoping that typescript could support interface extending generic types like the following example:

    interface IHttpPromise<T extends {}> extends T{
        $resolved: boolean;
        $error: boolean;
    }

    interface IHttpPost {
        <T extends {}>(actionUrl: string, postData: any): IHttpPromise<T>;
    }

The use case is that an http request is initiated and the IHttpPost method returns an object which gets populated when the request completes. In angular this pattern is being used by the $resource service (see definitelyTyped IResource declaration here).

Is this feasible?

Thanks in advance,

Andreas

PS: I have seen this issue in codeplex but couldn't find it here.

andreasbotsikas avatar Mar 06 '15 14:03 andreasbotsikas

Another case where this would help ergonomics is when coupling it with classes. For example, imagine an ORM:

class Model<Attributes> {
  constructor(attributes:Attributes);
  // ...
}
interface Model<Attributes> extends Attributes {}

// ---

interface UserAttributes {
  id:number;
  name:string;
}

class User extends Model<UserAttributes> {
  firstName() {
    return this.name.split(/\s+/)[0]; // `name` should be available.
  }
}

nevir avatar Jan 05 '17 18:01 nevir

Just came across a need for this when declaring a base entity class as part of a setup to work with Azure Table Storage. I want to create a base entity class that absorbs all the properties of the data passed into it. That base class has a generic parameter of the data it receives.

So ultimately that generic parameter is what needs to be implemented/extended.

atrauzzi avatar Jan 24 '17 09:01 atrauzzi

@louy Except that it cannot be implemented by a class:

class Foo implements Instance<Bar> {...}

[ts] A class may only implement another class or interface.

andraaspar avatar Feb 09 '17 12:02 andraaspar

@andraaspar yes that's why it's not optimal. it's a type not an interface.

louy avatar Feb 09 '17 12:02 louy

i think this can be done in a clean way with keyof now though.

louy avatar Feb 09 '17 12:02 louy

I have a case where a method converts an removes some properties of a base class, which should also work on interfaces inherited from that class. The inherited interfaces would then change the base class they're inherited from:

interface A {a: string}
interface AA extends A {b: string}
interface AB extends A {b_conv: string}

// Converts any type that inherits AA to the same type inheriting AB
const converter = <T extends AA>(x: T): Pick<T, Exclude<keyof T, "b">> & AB => <any>x

// Would really like this to be an interface extending T, not just an intersection type (although admittedly, this is awesome anyways, but that's not really the point here)
type X<T extends A = AA> = T & {yoho: number}

const before: X = {a: "a", b: "b", yoho: 10}
const after: X<AB> = converter(before)
const awesomeString = `${after.a} ${after.b_conv} ${after.yoho}`

Having the X type a first class interface would make this even cooler, although I'm just amazed by the new advanced types in TS lately. It's a new world of type programming!

tvedtorama avatar May 03 '18 06:05 tvedtorama

yes, please.

SalvatorePreviti avatar Jul 30 '18 11:07 SalvatorePreviti

@DanielRosenwasser I agree. For example:

interface Animal {
  numberOfLegs: number;
}

interface Male {
  yChromosome: any;
}

interface Female<A> extends A { //Error: An interface may only extend a class or another interface.
  mate(male:Male & A): (A & (Male | Female<A>))[];
}

Still gets an error of: An interface may only extend a class or another interface.

This is exactly my use-case (minus the precise example objects ;)) and my problem. +1 For this feature.

kael-shipman avatar Sep 23 '18 03:09 kael-shipman

That will resolve my issues with : https://github.com/bterlson/strict-event-emitter-types

I will be able then to pass the T with Events to the StrictEventEmitter.

TheAifam5 avatar Oct 28 '18 21:10 TheAifam5

I'm not sure if this is still an open issue, but I found this after receiving the error when you make an interface extend a generic. In my case, I was trying to wrap Database results in a type which enumerates the extra keys added by the mysql library. What I ended up doing isn't in the discussion yet, so I thought I'd list it.

In my models file, I added

export interface DBInfo {
    insertId?: number;
    affectedRows?: number;
    changedRows?: number;
}

export type DBResponse<T> = DBInfo & T;

then, in other files, I can list the return type as DBResponse<User> and it attaches the extra keys correctly.

localyost3000 avatar Dec 09 '18 19:12 localyost3000

I use this small variant:

type Props<T = {}> = T & {
  id: string
}

type MyProps = {
  message: string
}

// Usage
class MyComponent {
  public props: Props<MyProps> = {
    id: 'ef6872a'
    message: 'Hola!'
  }
}

joseluisq avatar May 07 '19 07:05 joseluisq

Since, the type declarations cannot return this from method calls. I think, having ability for interfaces to extend generics will be super helpful.

thetutlage avatar Dec 12 '19 17:12 thetutlage

I would like to know more how interfaces extending generics is different and why is it more difficult than intersection?

interface BaseItem<T> extends T {
  title: string
  help?: string
}

type BaseItem<T> = T & {
  title: string
  help?: string
}

ackvf avatar Feb 03 '20 16:02 ackvf

The issue with the type-instead-of-interface hack is that you cannot extend it for a class.

lazarljubenovic avatar Sep 11 '20 12:09 lazarljubenovic

I think this feature is well-addressed by intersections.

RyanCavanaugh avatar Sep 11 '20 16:09 RyanCavanaugh

@RyanCavanaugh This feature is not adequately served by intersections, as @lazarljubenovic and others have pointed out in this thread, because types don't play well with classes. I'm consuming a JavaScript library that's using some "old school" JS techniques to achieve something similar to mixins/multiple inheritance, and without this feature I've not yet found a way for the type system to accurately reflect the shape of my classes. This forces me to discard the type system via any casts or @ts-ignore comments any time I need to access a class member that TypeScript is unaware of, which is not a sustainable solution for the long term. A generic interface that could inherit the members of its type argument would seamlessly and painlessly solve this issue, but instead I'm spending valuable hours struggling to hack the type system into giving me accurate feedback.

dannymcgee avatar Nov 26 '20 21:11 dannymcgee

@dannymcgee I went through pretty much every example in this thread and confirmed that available alternates work, e.g. this is legal now (it didn't use to be)

type BaseItem<T> = T & {
  title: string
  help?: string
}

class M implements BaseItem<{x: string}> {
  x: string;
  title: string;
  help: string;
}

The OP is from 2015 and many interim comments refer scenarios that now work transparently or with minimal changes. I think a new issue that clearly outlines whatever shortcomings exist about current patterns and what would upsides could exist from U extends T (as compared to U & T in an alias) would be worthwhile.

RyanCavanaugh avatar Nov 30 '20 19:11 RyanCavanaugh