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!
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.
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.
Yes you can do it.
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.
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> {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With