工具泛型

typeof

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

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

  • 用来遍历枚举类型:

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

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

keyof

// 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

infer

ReturnType

Required

Pick

Omit

Exclude

Extract

Record

  • 此类型包含一组指定的属性且都是必填。

  • 具体的复杂业务场景中,一般会接合 Pick 、Partial 等组合使用,从而过滤和重组出新的类型定义。

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

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

Partial

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

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

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

NonNullable

Parameters

ConstructorParameters

readonly

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

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.

最后更新于

这有帮助吗?