Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining typescript generics with type safety

Can you define generics with safe types, as you can with c#?

E.g.

public bool Foo<T>() where T : struct { /* */ }

Typescript now has generics, but can I perform a similar action?

Thanks.

like image 349
Tim Avatar asked Jul 15 '13 13:07

Tim


People also ask

How do you define a generic type in TypeScript?

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.

How do you pass a generic type as parameter TypeScript?

Assigning Generic ParametersBy passing in the type with the <number> code, you are explicitly letting TypeScript know that you want the generic type parameter T of the identity function to be of type number . This will enforce the number type as the argument and the return value.

Are generic classes type safe?

Why Generics? The Object is the superclass of all other classes, and Object reference can refer to any object. These features lack type safety. Generics add that type of safety feature.

How do generics work 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.


1 Answers

Ok it seems you can do this:

Foo<T extends IBar>() { /* */ } 

And that seems to make all calls require the T to implement IBar.

like image 72
Tim Avatar answered Sep 21 '22 12:09

Tim