In this article, we'll take a dive into TypeScript types, exploring the built-in types, advanced type concepts, and examples. Let's get started! 🎉
Basic Types 📚
1. number
🔢
Represents numeric values like integers and floating-point numbers.
let age: number = 25;
2. string
🔡
Denotes textual data, typically enclosed in single or double quotes.
let name: string = "Alice";
3. boolean
✅❌
Represents true or false values.
let isActive: boolean = true;
4. any
🌌
A flexible type that allows dynamic types, similar to plain JavaScript.
let dynamicValue: any = 42;
dynamicValue = "Hello!";
5. void
🌫️
Used for functions that don't return a value.
function logMessage(): void {
console.log("Logged!");
}
6. null
and undefined
🚫
Denote the absence of a value. They are separate types and can be assigned to their respective types.
let maybeNull: null = null;
let maybeUndefined: undefined = undefined;
7. never
❌
Represents values that never occur, often used for functions that throw exceptions or enter infinite loops.
function throwError(message: string): never {
throw new Error(message);
}
8. Object 🏛️
Represents non-primitive types, i.e., anything that is not a number, string, boolean, null, or undefined.
let person: object = { name: "Bob", age: 30 };
or
let person: Record<string, string> = { name: "Bob" };
or
let person: { name: string } = { name: "Bob" };
9. symbol
🔑
Creates unique and immutable values, often used as object property keys.
const uniqueKey: symbol = Symbol("unique");
10. Enumerated types (enum
) 🌈
A set of named constant values, great for improving code readability.
enum Color {
Red,
Green,
Blue,
}
let chosenColor: Color = Color.Green;
11. Tuple types 📦
Allows defining an array with fixed types and known lengths.
let person: [string, number] = ["Alice", 25];
12. Array types 📚
Denotes arrays of a specific type.
let numbers: number[] = [1, 2, 3, 4, 5];
13. Type aliases ✍️
Create custom names for types, making complex types more readable.
type Point = { x: number; y: number };
let coordinates: Point = { x: 10, y: 20 };
Advanced Type 🌟
Union Types 🌐
Combining multiple types using the |
operator.
let value: string | number = "Hello";
value = 42;
Intersection Types ⚓
Combining multiple types into one, resulting in the presence of all properties from each type.
type Nameable = { name: string };
type Ageable = { age: number };
type Person = Nameable & Ageable;
let person: Person = { name: "Alice", age: 30 };
Example 🚀
1. Function Signature ✍️
Define a function signature using a type.
type MathOperation = (a: number, b: number) => number;
const add: MathOperation = (a, b) => a + b;
2. Different Type 🗃️
Using type unions to handle different data structures.
type DataStructure = string[] | number[] | object[];
function printLength(data: DataStructure) {
console.log(data.length);
}
Top comments (0)