Does TypeScript provide type aliases?

So I would like to use an alias for an ugly type that looks like this:

Maybe<Promise<Paged<Carrier>, Problem>>[] 

Something like:

 import Response = Maybe<Promise<Paged<Carrier>, Problem>>[]; 

Is there a way to make type aliases in TypeScript?

+71
typescript
Feb 17 '14 at 21:33
source share
3 answers

Version 1.4 Typescript supports type aliases ( source ).

Typical Aliases

Now you can define an alias for the type using the type keyword:

 type PrimitiveArray = Array<string|number|boolean>; type MyNumber = number; type NgScope = ng.IScope; type Callback = () => void; 

Typical aliases are exactly the same as their original types; these are just alternative names.

And from version 1.6, Typescript supports generic type aliases ( source ).

General Aliases

Leading up to Typescript 1.6, type aliases were limited to simple aliases that shortened long type names. Unfortunately, not being able to make these general, they had limited use. We now allow type aliases to be universal, giving them full expressiveness.

 type switcharoo<T, U> = (u: U, t:T)=>T; var f: switcharoo<number, string>; f("bob", 4); 
+103
Feb 05 '15 at 12:00
source share

TypeScript supports import, for example:

 module A { export class c { d: any; } } module B { import moduleA = A; var e: moduleA.c = new moduleA.c(); } module B2 { import Ac = Ac; var e: Ac = new Ac(); } 

Update 1

Since TS 1.4 we can use type declarations:

 type MyHandler = (myArgument: string) => void; var handler: MyHandler; 

Since TS 1.6 you can use local type declarations:

 function f() { if (true) { interface T { x: number } let v: T; vx = 5; } else { interface T { x: string } let v: T; vx = "hello"; } } 
+10
Feb 18 '14 at 6:10
source share

The solution for the poor is to declare a dummy variable (e.g. t ) with the required type and use typeof t instead of expressing a long type:

 var t: {(x: number, f: {(foo: string, bar: boolean): void}): void};

 var f: typeof t;
 var g: typeof t;
+7
Aug 07 '14 at 23:50
source share



All Articles