xxxxxxxxxx
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.
xxxxxxxxxx
type alphanumeric = string | number;
let input: alphanumeric;
input = 100; // valid
input = 'Hi'; // valid
input = false; // Compiler error
Code language: JavaScript (javascript)