Posts > TS Basic: Type Aliases
July 22, 2023
Type aliases are a way of creating a custom name for your type variables, functions and objects for reusability and readability.
type MyString = string;
const message : MyString = 'Hello world'
type Point = {
x: number,
y: number,
}
const origin : Point = [ x: 0, y: 0 ];
type NumberOrString = number | string;
const value : NumberOrString = 42;
const value : NumberOrString = 'hello';
type MathOperation = (x: number, y:number) => number;
const add : MathOperation = (a,b) => a + b;
const result = add(2,3); // 5
type Shape = Square | Circle | Triangle;
type Square = { type: 'square'; sideLength: number };
type Circle = { type: 'circle'; radius: number };
type Triangle = { type: 'triangle'; base: number; height: number; };
function calculateArea(shape: Shape): number {
switch (shape.type) {
case 'square':
return shape.sideLength ** 2;
case 'circle':
return Math.PI * shape.radius ** 2;
case 'triangle':
return (shape.base * shape.height) / 2;
default:
throw new Error('Invalid shape type');
}
}
const squareArea = calculateArea(square);
const circleArea = calculateArea(circle);
const triangleArea = calculateArea(triangle);
Type aliases can make your code more expressive and allow you to create reusable types that can simplify your type annotation throughout your codebase.
👌Note that aliases are only aliases - you cannot use type aliased to create different distinct "version" of the same type.