Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are generic type aliases possible in TypeScript?

TypeScript 1.4 introduced type aliases. The examples show how to use aliases like type MyGreeter = Greeter<string> but is it possible to have generic aliases?

The following examples do not work:

type GenericAlias<T> = OriginalType<T>
type GenericAlias = OriginalType<T>

Is it at all possible to alias generic types without typecasting them?

like image 445
Dynalon Avatar asked Mar 14 '15 17:03

Dynalon


People also ask

Does TypeScript support generic?

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.

What are aliases in TypeScript?

In Typescript, Type aliases give a type a new name. They are similar to interfaces in that they can be used to name primitives and any other kinds that you'd have to define by hand otherwise. Aliasing doesn't truly create a new type; instead, it gives that type a new name.

What is generic method 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.

What encloses a generic in TypeScript?

In TypeScript, the syntax for generics is rather simple. We use angle brackets to enclose the generic type-parameter.


1 Answers

As of TypeScript 1.6 this is now possible.

// from #1616:
type Lazy<T> = T | (() => T);

var s: Lazy<string>;
s = "eager";
s = () => "lazy";

Pre-1.6 answer

No, not yet. You can see developments on this in issue #1616.

As for when this feature will be available...

Lately we've been quite busy with ES6 alignment and the recently announced Angular 2.0 related features. We will get to (re)evaluating some of these type system specific issues but there's no concrete date for issues like this at the moment. - Source

like image 173
David Sherret Avatar answered Oct 16 '22 04:10

David Sherret