typescript类型体操

angrybird2332023-04-17FrontendTypescript

在 TypeScript 中,类型体操是使用高级类型系统功能进行类型处理和转换的一种技巧。以下是一些常用的类型体操技巧,包括详细说明和示例:

1. 类型别名(Type Aliases)

类型别名用于为类型创建新的名称。

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

const p: Point = { x: 10, y: 20 };

2. 联合类型(Union Types)

联合类型允许一个变量可以是几种类型之一。

type ID = number | string;

let userId: ID;
userId = 123;
userId = "abc";

3. 交叉类型(Intersection Types)

交叉类型将多个类型合并为一个类型。

type Name = {
  firstName: string;
  lastName: string;
};

type Address = {
  city: string;
  country: string;
};

type Person = Name & Address;

const person: Person = {
  firstName: "John",
  lastName: "Doe",
  city: "New York",
  country: "USA",
};

4. 条件类型(Conditional Types)

条件类型根据某个条件选择一种类型。

type IsString<T> = T extends string ? "yes" : "no";

type A = IsString<string>;  // "yes"
type B = IsString<number>;  // "no"

5. 映射类型(Mapped Types)

映射类型根据旧类型创建新类型。

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

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

const p: Readonly<Point> = { x: 10, y: 20 };
// p.x = 30; // Error: cannot assign to 'x' because it is a read-only property

6. 索引类型(Index Types)

索引类型用于访问类型的属性。

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

type NameType = Person["name"];  // string

7. 元组类型(Tuple Types)

元组类型用于表示固定数量的不同类型的元素。

type Tuple = [string, number];

const tuple: Tuple = ["hello", 10];

8. 类型推断(Type Inference)

TypeScript 会根据代码自动推断类型。

let x = 10;  // x is inferred as number

9. 泛型(Generics)

泛型使得函数、接口或类能够处理多种类型。

function identity<T>(arg: T): T {
  return arg;
}

const num = identity<number>(123);
const str = identity<string>("hello");

10. 实用类型(Utility Types)

TypeScript 提供了一些内置的实用类型,如 PartialPickOmit 等。

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

type PartialPerson = Partial<Person>;  // All properties are optional
type NameAndAge = Pick<Person, "name" | "age">;  // Only name and age
type PersonWithoutAddress = Omit<Person, "address">;  // All except address

11. 递归类型(Recursive Types)

递归类型用于表示嵌套结构或无限深度的数据结构。

type NestedObject = {
  value: string;
  children?: NestedObject[];
};

const example: NestedObject = {
  value: "root",
  children: [
    {
      value: "child1",
      children: [
        { value: "child1.1" },
        { value: "child1.2" }
      ]
    },
    { value: "child2" }
  ]
};

12. 深度只读类型(DeepReadonly)

通过递归将对象的每一层都设为只读。

type DeepReadonly<T> = {
  readonly [P in keyof T]: DeepReadonly<T[P]>;
};

type ExampleObject = {
  a: {
    b: {
      c: string;
    }
  }
};

const example: DeepReadonly<ExampleObject> = {
  a: {
    b: {
      c: "value"
    }
  }
};

最后更新时间 9/4/2024, 8:14:48 AM