Suggestion: Interface extend generic type
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
Is this feasible?
Thanks in advance,
Andreas
PS: I have seen this issue in codeplex but couldn't find it here.
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?
+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().
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.
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");
Is this a suggestion his it could be implemented, or already a working feature?
@pgrm, intersection types is part of TypeScript 1.6, here is the release blog
Will I be able to do something like this:
function addMetadata<T>(data: T): T & MetaData {
....
}
@ronzeidman yes, that should work.
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
@andreasbotsikas, any other scenarios not captured in the previous discussion?
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!
While certain use-cases have been addressed, I'm not sure that this should be closed.
@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 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 Good real world example.
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.
+1
+1
+1
@louy GREAT!!!