Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Generic and Non-Generic Version of Type

I have a very short question, I'm trying to make two classes in typescript:

export class ServiceResponse { }

export class ServiceResponse<T> extends ServiceResponse {}

but according to typescript, these are duplicate identifiers. Is it possible to use the same name with a generic type argument in typescript? Is this a problem that someone has solved before? I come from a C# background, where this pattern is fairly common.

Thanks!

like image 897
Jonesopolis Avatar asked Feb 04 '18 05:02

Jonesopolis


People also ask

What is a generic type in TypeScript?

The TypeScript documentation explains Generics as “being able to create a component that can work over a variety of types rather than a single one.” Great! That gives us a basic idea. We are going to use Generics to create some kind of reusable component that can work for a variety of types.

Why is generic used in TypeScript?

TypeScript fully supports generics as a way to introduce type-safety into components that accept arguments and return values whose type will be indeterminate until they are consumed later in your code.

Can a generic class be subclass of non generic?

Yes you can do it.

How do I know the generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.


1 Answers

Aleksey answered the question in the comment above, but just wanted to provide an actual answer with more context for future reference

This is expected since the Typescript type annotations (including the generic type parameter <T> here) are stripped out when compiled down to JavaScript, and you end up with two classes with the same name, hence the duplicate identifier error.

In order to define a generic and non-generic versions of the same class, you can specify a default value for your generic type parameter:

export class ServiceResponse<T = void> {
}
like image 122
AbdouMoumen Avatar answered Oct 13 '22 00:10

AbdouMoumen