Understanding Types in TypeScript
TypeScript is a powerful, statically typed superset of JavaScript that helps developers write safer and more maintainable code. One of its key features is its robust type system. In this blog, we will explore the most important types in TypeScript and provide examples to illustrate their use.
1. Primitive Types
TypeScript includes all JavaScript primitive types, ensuring that variables are strongly typed.
a. String
Represents textual data.
let name: string = "John Doe";
let greeting: string = `Hello, ${name}!`;
b. Number
Represents both integer and floating-point numbers.
let age: number = 30;
let height: number = 5.9;
c. Boolean
Represents true or false values.
let isLoggedIn: boolean = true;
let hasAccess: boolean = false;
d. Null and Undefined
null
: Represents an intentional absence of value.undefined
: Represents an uninitialized variable.
let emptyValue: null = null;
let uninitializedValue: undefined = undefined;
2. Array
Arrays in TypeScript can store a collection of elements of the same type or mixed types (if explicitly declared).
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Charlie"];
let mixed: (string | number)[] = ["John", 25, "Doe", 40];
3. Tuple
A tuple allows you to define an array with fixed types and a fixed number of elements.
let person: [string, number] = ["Alice", 30];
let coordinates: [number, number, number] = [12.34, 56.78, 90.12];
4. Enum
Enums are a way of giving more friendly names to sets of numeric or string values.
enum Role {
Admin,
Editor,
Viewer,
}
let userRole: Role = Role.Admin;
You can also use string enums:
enum Status {
Success = "SUCCESS",
Failure = "FAILURE",
}
let currentStatus: Status = Status.Success;
5. Any
The any
type can hold any value and is useful for dynamic content. However, its use should be minimized to retain type safety.
let randomValue: any = 42;
randomValue = "Hello";
randomValue = true;
6. Void
The void
type is used for functions that do not return a value.
function logMessage(message: string): void {
console.log(message);
}
7. Never
The never
type represents values that never occur. It is often used in functions that throw errors or have infinite loops.
function throwError(message: string): never {
throw new Error(message);
}
8. Object
The object
type is a non-primitive type that represents any non-primitive value.
let person: object = {
name: "Alice",
age: 30,
};
9. Union Types
Union types allow a variable to hold one of several types.
let identifier: string | number;
identifier = "ABC123";
identifier = 12345;
10. Intersection Types
Intersection types combine multiple types into one.
type User = {
name: string;
age: number;
};
type Admin = {
role: string;
};
type AdminUser = User & Admin;
let admin: AdminUser = {
name: "Alice",
age: 30,
role: "Admin",
};
11. Literal Types
Literal types allow you to specify exact values a variable can hold.
let direction: "up" | "down" | "left" | "right";
direction = "up";
12. Type Aliases
Type aliases allow you to create custom types with meaningful names.
type Point = {
x: number;
y: number;
};
let origin: Point = { x: 0, y: 0 };
13. Interfaces
Interfaces define the structure of an object and are useful for type-checking.
interface User {
name: string;
age: number;
isAdmin?: boolean; // Optional property
}
let user: User = {
name: "Alice",
age: 30,
};
14. Functions
TypeScript supports function parameters and return type annotations.
function add(a: number, b: number): number {
return a + b;
}
function greet(name: string): string {
return `Hello, ${name}!`;
}
Conclusion
TypeScript’s type system is vast and versatile, providing tools to write clear, concise, and robust code. By understanding and using these types effectively, developers can catch errors early and build applications with confidence. Whether you’re new to TypeScript or looking to refine your skills, mastering these types is an essential step.