乐闻世界logo
搜索文章和话题

What are advanced types in TypeScript?

1个答案

1

Advanced types in TypeScript provide richer ways to describe the types of variables or functions, thereby enhancing strong type checking and code readability. Here are some common advanced types:

  1. Union Types: Union types allow a variable to be one of several types. For example, number | string indicates that the variable can be of type number or string.

    Example:

    typescript
    function printId(id: number | string) { console.log(`Your ID is: ${id}`); }
  2. Intersection Types: Intersection types combine multiple types into a single type, enabling you to merge properties from different types together.

    Example:

    typescript
    type Employee = { name: string; startDate: Date; }; type Manager = Employee & { group: string; }; let manager: Manager = { name: "Alice", startDate: new Date(), group: "Sales" };
  3. Type Aliases: Type aliases allow you to assign a new name to a type, making it easier to reuse and reference across your codebase.

    Example:

    typescript
    type Point = { x: number; y: number; }; function printCoord(pt: Point) { console.log(`The coordinate's x value: ${pt.x}`); console.log(`The coordinate's y value: ${pt.y}`); }
  4. Discriminated Unions: Discriminated unions are a pattern that combines union types with literal types, commonly used to implement type-safe states or object variants.

    Example:

    typescript
    interface Square { kind: "square"; size: number; } interface Rectangle { kind: "rectangle"; width: number; height: number; } type Shape = Square | Rectangle; function area(s: Shape) { switch (s.kind) { case "square": return s.size * s.size; case "rectangle": return s.width * s.height; } }
  5. Generics: Generics provide a way to create reusable components that support multiple types while maintaining type safety.

    Example:

    typescript
    function identity<T>(arg: T): T { return arg; } let output = identity<string>("myString"); let outputNumber = identity<number>(100);

These advanced types not only improve code flexibility and reusability but also help developers catch more errors during compilation, thereby enhancing application stability and quality.

2024年8月2日 13:51 回复

你的答案