type alias in typescript 1

type alias in typescript

type StringAlias = string;
type NumberAlias = number;
// aliases for 'normal' types

type SixAlias = 6;         
type MyFavouriteFood = "burger"; 
// aliases for 'literal' types
// these are usually useless on their own

type Food = MyFavouriteFood | "pizza" | "pasta" | "salad";
// they get useful when you combine them:
// a Food can be one of these choices.

type Foods = Food[];
// this is an alias for an array of Foods.

type SuccessfulResponse = {
	message: string,
  	statusCode: number,
  	attachment?: string,
	preferredFoods?: Foods,
}                          
// Now we define a SuccessfulResponse type as the type of a
// JS literal object with two required and two optional attributes.
// Note that you could also use an interface in this case.

type SuccessfulResponseHandler = (res: SuccessfulResponse) => void;
// This is a type alias for a function.


// tl;dr: You can alias every type in TypeScript and chain them.
// This is very useful for reusability and readability.

Here is what the above code is Doing:
1. We define a type alias for a string and a number.
2. We define a type alias for the number 6 and the string “burger”.
3. We define a type alias for a union of four strings.
4. We define a type alias for an array of the type defined in 3.
5. We define a type alias for a JS literal object with two required and two optional attributes.
6. We define a type alias for a function.

Similar Posts