Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript generic interface<T> extending same name

This obviously works fine in C# but not typescript, is there a way around it or will I just have to use different names?

export interface IThing<T> extends IThing {
 Value: T;
}

export interface IThing {
Name?: string;
ValueStr?: string;
Type?: string;
}

I get 'All declarations of IThing must have identical type parameters'

Apologies if I'm being dense!

like image 642
Michael Harper Avatar asked Feb 15 '18 15:02

Michael Harper


1 Answers

You need to use different names, only name matters when identifying the interface not the number of generic type parameters.

Generics are erased at compile time in Typescript, so there is no way to distinguish between different instantiations of a generic class. Although interfaces are only a compile time construct and could possibly have been differentiated by name as well as number of generic parameters, my guess is that since classes work this way it was decided to make interfaces work in the same way.

One work around would be to use a default type argument for the interface:

export interface IThing<T = any> {
    Name?: string;
    ValueStr?: string;
    Type?: string; 
    Value: T;
}

var d: IThing;
var foo: IThing<number> 
like image 100
Titian Cernicova-Dragomir Avatar answered Nov 06 '22 02:11

Titian Cernicova-Dragomir