TypeScript enforces types, making it easier to catch errors early. You can declare variables with specific types like number, string, etc.
let age: number = 20;
if (age < 50) {
age += 10;
console.log(age); // Output: 30
}In this example, the age variable is defined as a number. We also have a simple condition that checks the age and updates its value accordingly.
Enums allow us to define a set of named constants. TypeScript's enums can be both numeric and string-based.
const enum sizes {
small = 1 + 20, // Output: 21
medium,
large,
}
const mySize = sizes.medium;
const yourSize = sizes.large;
console.log(mySize, yourSize); // Output: 22 23Here, sizes is an enum with three sizes: small, medium, and large, with automatic increment after the first value.
Functions in TypeScript can have return types, optional parameters, and more.
function incomeTax(income: number): number {
if (income > 50_000 && income < 75_000) {
return income * 1.15; // Tax applied
}
return income; // No tax applied
}
let income: number = 20_000;
console.log(incomeTax(income)); // Output: 20000function incomeTax2(income: number, year?: number): number {
if (income > 50_000 && income < 75_000 && (year || 2022) >= 2024) {
return income * 1.15;
}
return income;
}
console.log(incomeTax2(20_000)); // Output: 20000Optional parameters, like year?, allow us to pass or skip parameters while calling functions.
Objects in TypeScript can be defined with specific properties, and some properties can be marked as readonly to prevent reassignment.
const employee: {
readonly id: number;
name: string;
age?: number; // Optional property
retire: (date: Date) => void;
} = {
id: 1,
name: "",
retire: (date: Date) => {
console.log(date);
},
};
employee.name = "Trishon";
employee.age = 25;
// employee.id = 2; // Error: Cannot assign to 'id' because it is a read-only propertyThis defines an employee object where id is readonly, meaning it cannot be changed after assignment.
Type aliases allow us to define custom types to be reused across the codebase.
type EmployeeType = {
readonly id: number;
name: string;
age?: number;
retire: (date: Date) => void;
};
const Employee: EmployeeType = {
id: 1,
name: "",
age,
retire: (date: Date) => {
console.log(date);
},
};EmployeeType is a custom type that can be reused to define different employee objects.
Union types allow a variable to have multiple types. You can use union types for flexibility.
function kgToLbs(weight: number | string) {
if (typeof weight === "number") return weight * 2.2;
else return parseInt(weight) * 2.2;
}
console.log(kgToLbs(10)); // Output: 22
console.log(kgToLbs("10")); // Output: 22This function accepts either a number or a string, processes it accordingly, and returns the result.
Intersection types combine multiple types into one.
type Draggable = {
drag: () => void;
};
type Resizable = {
resizes: () => void;
};
type UIWidget = Draggable & Resizable;
const textBox: UIWidget = {
drag: () => {},
resizes: () => {},
};UIWidget inherits both Draggable and Resizable types, meaning the object must implement both methods.
Literal types allow you to specify exact values for types.
type Quantity = 50 | 100 | 150; let quantity: Quantity = 100; type Sizes = "small" | "medium" | "large"; let shirtSize: Sizes = "small";
Here, Quantity can only be 50, 100, or 150, and Sizes can only be small, medium, or large.
Nullable types allow a variable to be either a specific type or null or undefined.
function greet(name: string | null | undefined) {
if (name) console.log(name.toUpperCase());
else console.log("Hola!");
}
greet("Hello!"); // Output: HELLO!
greet(null); // Output: Hola!
greet(undefined); // Output: Hola!This function accepts string, null, or undefined and handles them accordingly.
Optional chaining allows you to access properties of an object that may not exist.
type Customer = {
birthDate?: Date;
};
function getCustomer(id: number): Customer | null | undefined {
return id === 0 ? null : { birthDate: new Date() };
}
let customer = getCustomer(1);
console.log(customer?.birthDate?.getFullYear()); // Output: current year or undefinedHere, if customer or birthDate is null or undefined, the optional chaining operator ?. prevents the code from throwing an error.
You can also conditionally call a function if it exists.
let log: any = (message: string) => console.log(message);
let log1: any = null;
log1?.("a"); // No output, as log1 is nullThe ?. ensures the function is called only if it exists.