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

I think it is actually quite common in JS to take an object, add properties or functions to it and return it. And I wouldn't know how else to define the return as a generic except

getRemoteObject<T>(id: string): IRemoteObject<T>;

interface IRemoteObject<T> extends T { save(); getRawObject(): T; ... }

I've just written a definition file for such a similar case and had to discribe in the comments the workaround to actually create an interface yourself which merges IRemoteObject<T> and T. For instance:

interface IUser {email: string; name: string; ...}
interface IRemoteUser extends IRemoteObject<IUser>, IUser { }

var user: IRemoteUser = getRemoteObject<IUser>('id');

Or did I miss any other way to implement this?

pgrm avatar May 07 '15 17:05 pgrm

+1! I think this is the best way to use TypeScript with Immutable js records. Also generally when you want to use the decorator pattern on generic types, such as with Radium.enhancer().

richardhuaaa avatar May 29 '15 00:05 richardhuaaa

Here's another example:

interface Animal {
  numberOfLegs: number;
}

interface MaleAnimal<A extends Animal> extends A {}

interface FemaleAnimal<A extends Animal, M extends MaleAnimal<A>> extends A {
  mate(father:M): Promise<A[]>;
}

This has two errors:

  • An interface may only extend a class or another interface.
  • Constraint of a type parameter cannot reference any type parameter from the same type parameter list.

eggers avatar Sep 04 '15 21:09 eggers

Why not use intersection types to model this? e.g.

interface Controller {
    name: string;
}

interface EventHandler {
    handel(event: string): void;
}

var MyEventHandelingControler: Controller & EventHandler;

MyEventHandelingControler.name;
MyEventHandelingControler.handel("event");

mhegazy avatar Sep 05 '15 00:09 mhegazy

Is this a suggestion his it could be implemented, or already a working feature?

pgrm avatar Sep 05 '15 06:09 pgrm

@pgrm, intersection types is part of TypeScript 1.6, here is the release blog

mhegazy avatar Sep 06 '15 22:09 mhegazy

Will I be able to do something like this:

function addMetadata<T>(data: T): T & MetaData {
     ....
}

ronzeidman avatar Sep 12 '15 06:09 ronzeidman

@ronzeidman yes, that should work.

DanielRosenwasser avatar Sep 12 '15 06:09 DanielRosenwasser

Yes the example seems to suggest that it should work also with generics:

function extend<T, U>(first: T, second: U): T & U {
    let result = <T & U> {};
    for (let id in first) {
        result[id] = first[id];
    }
    for (let id in second) {
        if (!result.hasOwnProperty(id)) {
            result[id] = second[id];
        }
    }
    return result;
}

var x = extend({ a: "hello" }, { b: 42 });
var s = x.a;
var n = x.b;

That solves what I wanted. So from my side this issue could be closed. thx @mhegazy

pgrm avatar Sep 12 '15 07:09 pgrm

@andreasbotsikas, any other scenarios not captured in the previous discussion?

mhegazy avatar Sep 12 '15 09:09 mhegazy

Yes and I like the fact that I transfer the logic to the function instead of declaring an interface that combines the 2 interfaces. My sample works with the following:

interface IHttpPromiseInfo{
     $resolved: boolean;
     $error: boolean;
}

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

Thanks for bringing this feature!

andreasbotsikas avatar Sep 12 '15 18:09 andreasbotsikas

While certain use-cases have been addressed, I'm not sure that this should be closed.

DanielRosenwasser avatar Sep 13 '15 07:09 DanielRosenwasser

@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.

eggers avatar Sep 14 '15 21:09 eggers

This would be a useful feature for working with OData GET responses.

http://www.odata.org/ > Step 2. Requesting an individual resource

OData mixes its own fields with a single response's fields. For example, given the following interface...

interface IPerson {
    FirstName: string;
    LastName: string;
}

...an OData response for a single entity would be...

// Shortened for brevity
{
    "@odata.context":"http://my-api#People/$entity(0000-0000-0000-0000)",
    "FirstName":"Russell",
    "LastName":"Whyte"
}

Right now, the best solutions for typing that response in a .d.ts would be having an IODataReponse contain "@odata.context"-style fields with an IPersonResponse extends IPerson, IODataResponse, or an intersection type:

interface IODataResponse {
    "@odata.context": string
}

// Yuck!
interface IPersonResponse extends IPerson, IODataResponse { }
// Less yuck
var response: IPerson & IODataResponse;

A much easier (and more elegant IMO) solution would be to have IODataResponse template a generic T and extend from that T:

interface IODataResponse<T> extends T { }

var response: IODataResponse<IPerson>;

JoshuaKGoldberg avatar Sep 22 '15 20:09 JoshuaKGoldberg

@JoshuaKGoldberg Good real world example.

eggers avatar Sep 22 '15 20:09 eggers

I think I found a solution for this:

  export type Instance<TInstance extends {}> = TInstance & {
    save(fn: (err: Error) => void): void;
  };

This can be used like:

find(fn: (err: Error, result: Instance<IAnimal>) => void): void;

find(function(err, animal) {
  animal.save((err) => void 0) // no problem
});

Still not optimal, but better.

louy avatar Dec 02 '15 12:12 louy

+1

DmitryEfimenko avatar Dec 02 '15 22:12 DmitryEfimenko

+1

lseguin42 avatar Mar 26 '16 15:03 lseguin42

+1

Heartnett avatar Apr 22 '16 07:04 Heartnett

@louy GREAT!!!

codedogfish avatar May 27 '16 03:05 codedogfish