Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics in TypeScript

Is there a way to parameterize a type with another type in TypeScript besides of using typed arrays?

It is really necessary with KnockoutJs.

like image 430
Trident D'Gao Avatar asked Oct 14 '12 21:10

Trident D'Gao


People also ask

What is generics 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.

Why are generics used?

Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.

What is a generic in code?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.


1 Answers

Generics are not supported as yet, though they are being considered. Here's what the spec has to say:

NOTE: TypeScript currently doesn’t support Generics, but we expect to include them in the final language. Since TypeScript’s static type system has no run-time manifestation, Generics will be based on “type erasure” and intended purely as a conduit for expressing parametric type relationships in interfaces, classes, and function signatures.

From the TypeScript language spec at the end of section 3.

like image 155
Brian Terlson Avatar answered Oct 30 '22 07:10

Brian Terlson