# 工具泛型

## typeof

typeof 的主要用途是在类型上下文中获取变量或者属性的类型

```ts
interface Person {
  name: string;
  age: number;
}
const user: Person = { name: "张三", age: 30 };
type User = typeof user; // type User = Person
const hoel: User = { name: "hoel", age: 5 };
```

## in

* 用来遍历枚举类型：

```ts
type Keys = "a" | "b" | "c";

type Obj = {
  [p in Keys]: any;
}; // -> { a: any, b: any, c: any }
```

## keyof

```ts
// key of 使用
interface People {
  name: string;
  age: number;
}
// keyof 取 interface 的键
// type keys = "name" | "age"
type keys = keyof People;
// 假设有一个 object 如下所示，
// 我们需要使用 typescript 实现一个 get 函数来获取它的属性值
const hoel: People = {
  name: "hoel",
  age: 12,
};

function get<T extends object, K extends keyof T>(o: T, name: K): T[K] {
  return o[name];
}
console.log(get(hoel, "age")); // 12
console.log(get(hoel, "name")); // hoel
// error 类型“"address"”的参数不能赋给类型“keyof People”的参数。
console.log(get(hoel, "address"));
```

## extends

```ts
```

## infer

## ReturnType

```ts
```

## Required

```ts
```

## Pick

```ts
```

## Omit

```ts
```

## Exclude

```ts
```

## Extract

```ts
```

## Record

* 此类型包含一组指定的属性且都是必填。
* 具体的复杂业务场景中，一般会接合 Pick 、Partial 等组合使用，从而过滤和重组出新的类型定义。

```ts
type Coord = Record<"x" | "y", number>;

// 等同于
type Coord = {
  x: number;
  y: number;
};
```

## Partial

* 将类型定义的所有属性都修改为可选。

```ts
type Coord = Partial<Record<'x' | 'y', number>>;

// 等同于
type Coord = {
	x?: number;
	y?: number;

```

## NonNullable

```ts
```

## Parameters

```ts
```

## ConstructorParameters

```ts
```

## readonly

* 将所有属性定义为自读。

```ts
type Coord = Readonly<Record<"x" | "y", number>>;

// 等同于
type Coord = {
  readonly x: number;
  readonly x: number;
};

// 如果进行了修改，则会报错：
const c: Coord = { x: 1, y: 1 };
c.x = 2; // Error: Cannot assign to 'x' because it is a read-only property.
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://shenjunhong.gitbook.io/blog/ts/gong-ju-fan-xing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
