TypeScript allows to create reuseable aliases for a simple, intersection, unions, tuples or any other valid TypeScript types.
To declare an alias we need to use the following syntax:
type myTypeName = <a valid TypeScript type>
Examples
Simple types
type chars = string;
function show(param: chars): void {
console.log(param);
}
show("hello"); Outputhello
Union types
type num = number | string;
function square(n: num): number {
if (typeof n === 'string') {
n = parseInt(n);
}
return Math.pow(n, 2);
}
console.log(square(3));
console.log(square("5")); Output9 25
Object properties/function/array types
//object properties
type Product = { name: string, price: number };
let p: Product = {price: 100, name: 'Monitor'};
console.log(p);
//function
type StringRemover = (input: string, index: number) => string;
let remover: StringRemover = function (str: string, i: number): string {
return str.substring(i);
}
let s = remover("Hi there", 3);
console.log(s);
//array
type State = [string, boolean];
let a: State = ["active", true];
console.log(a);
Output{ price: 100, name: 'Monitor' } there [ 'active', true ]
Using Literals
We we declare aliases with union types and a number of literal values to get enum-like behavior:
type Alignment = "Left" | "RIGHT" | "CENTER";
function doAlign(alignment: Alignment):void{
console.log(alignment);
}
doAlign("Left");//should be one of the above three values (case sensitive)
type WIDTH = 100 | 200 | 300;
function setWidth(w: WIDTH){
console.log(w);
}
setWidth(100);//should be one of the above three numbers OutputLeft 100
Example ProjectDependencies and Technologies Used: |