Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does TypeScript allow type aliases?

So I wish I could use an alias to 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 do type aliases in TypeScript?

like image 714
Trident D'Gao Avatar asked Feb 17 '14 21:02

Trident D'Gao


People also ask

What is the difference between type alias and interface in TypeScript?

“One difference is, that interfaces create a new name that is used everywhere. Type aliases don't create a new name — for instance, error messages won't use the alias name.”

What are type aliases in JavaScript?

A type alias is basically a name for any type. Type aliases can be used to represent not only primitives but also object types, union types, tuples and intersections.

What is type assertion in TypeScript?

In Typescript, Type assertion is a technique that informs the compiler about the type of a variable. Type assertion is similar to typecasting but it doesn't reconstruct code. You can use type assertion to specify a value's type and tell the compiler not to deduce it.

Should I use type or interface TypeScript?

Interfaces are most recommended for defining new objects or methods or properties of an object where it will receive a specific component. Hence interface works better when using objects and method objects. Therefore it is our choice to choose between types or interface according to the program needs.


1 Answers

From version 1.4 Typescript supports type aliases (source).

Type Aliases

You can now define an alias for a type using the type keyword:

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

Type aliases are exactly the same as their original types; they are simply alternative names.

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

Generic type aliases

Leading up to TypeScript 1.6, type aliases were restricted to being simple aliases that shortened long type names. Unfortunately, without being able to make these generic, they had limited use. We now allow type aliases to be generic, giving them full expressive capability.

type switcharoo<T, U> = (u: U, t:T)=>T; var f: switcharoo<number, string>; f("bob", 4); 
like image 116
Mariusz Pawelski Avatar answered Sep 28 '22 09:09

Mariusz Pawelski