Skip to main content

Archive

Show more

Advanced Types in TypeScript

Advanced Types in TypeScript

TypeScript provides several advanced types that enhance the flexibility and power of the type system. These types allow for more precise type definitions and can help create more robust and maintainable code. This guide covers some of the key advanced types in TypeScript.


Intersection Types

Intersection types combine multiple types into one. This allows you to create a type that has all the properties of the intersected types:


interface Person {
  name: string;
}

interface Employee {
  employeeId: number;
}

type EmployeePerson = Person & Employee;

let employee: EmployeePerson = {
  name: "Alice",
  employeeId: 1234
};

console.log(employee); // Output: { name: 'Alice', employeeId: 1234 }

Union Types

Union types allow a value to be one of several types. This is useful when a value can be more than one type:


let value: string | number;

value = "Hello";
console.log(value); // Output: Hello

value = 42;
console.log(value); // Output: 42

Type Guards

Type guards are functions or conditions that allow TypeScript to infer a more specific type within a block of code:


function isString(value: unknown): value is string {
  return typeof value === "string";
}

function printValue(value: string | number) {
  if (isString(value)) {
    console.log(`String: ${value}`);
  } else {
    console.log(`Number: ${value}`);
  }
}

printValue("Hello"); // Output: String: Hello
printValue(42);      // Output: Number: 42

Type Aliases

Type aliases create a new name for a type. They are useful for creating more readable and reusable types:


type Point = {
  x: number;
  y: number;
};

let point: Point = { x: 10, y: 20 };
console.log(point); // Output: { x: 10, y: 20 }

Mapped Types

Mapped types generate new types based on existing ones, transforming each property according to specific rules:


type Readonly = {
  readonly [P in keyof T]: T[P];
};

type Person = {
  name: string;
  age: number;
};

type ReadonlyPerson = Readonly;

let person: ReadonlyPerson = { name: "Alice", age: 30 };
// person.age = 31; // Error: Cannot assign to 'age' because it is a read-only property.

Conditional Types

Conditional types enable complex type transformations based on a condition:


type IsString = T extends string ? "Yes" : "No";

type Test1 = IsString;  // "Yes"
type Test2 = IsString;  // "No"

console.log(Test1); // Output: "Yes"
console.log(Test2); // Output: "No"

Index Types

Index types enable dynamic property access and type checking for object properties:


function getProperty(obj: T, key: K): T[K] {
  return obj[key];
}

let person = { name: "Alice", age: 30 };
let name = getProperty(person, "name");
console.log(name); // Output: Alice

Conclusion

Advanced types in TypeScript provide powerful tools for creating flexible and precise type definitions. By using these types effectively, you can enhance the safety, readability, and maintainability of your TypeScript code. Whether you are combining types with intersections and unions, creating reusable type aliases, or transforming types with mapped and conditional types, TypeScript's advanced types can help you achieve your development goals.

Comments