跳到主要内容

操作符

常见的基础操作符(关键字),常用于类型判断

  • typeof: 获取类型
  • typeof and instanceof: 用于类型区分
  • keyof:获取 object 的所有键
  • in:遍历枚举类型. (遍历"a"|"b"|number)
  • T[K]索引访问,属性查找
  • extends:范型约束
  • - readonly ?: 减法、只读和可选修饰符
  • x ? Y : Z: 用于泛型类型、类型别名、函数参数类型的条件类型,和 extends 配合使用
  • !: 可空类型的空断言
  • as: 类型断言
  • is: 函数返回类型的类型保护
type Required<T> = {
[P in keyof T]-?: T[P];
};

Keyof

返回一个对象类型的键的联合类型

type Point = { x: number; y: number };
type P = keyof Point;
// type P = 'x' | 'y'

type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish;
// type A = number

type Mapish = { [k: string]: boolean };
type M = keyof Mapish;
// type M = string | number
//

typeof

typeof 可以推导出一个变量的类型,然后用于后续的类型编程 typeof 只能用于变量名或其属性值

function f() {
return { x: 10, y: 3 };
}
type P = ReturnType<f>;
// 'f' refers to a value,
// but is being used as a type here. Did you mean 'typeof f'?

function f() {
return { x: 10, y: 3 };
}
type P = ReturnType<typeof f>;

// type P = {
// x: number;
// y: number;
// }
// param是变量
keyof typeof param

keyof/typeof 的应用:操作对象索引的报错提示

const obj1 = { a: 1, b: 2, c: 3 };
const keys = ["a", "b"];
for (const key of keys) {
// 元素隐式具有"any"类型,因为类型为“string“作为key在obj1上找不到
console.log(obj1[key]);
}

如何正确地声明 keys 的类型呢?如下代码:

const keys: (keyof typeof obj1)[] = ['a', 'b'];

还有一种方法解决报错,怎么办呢?(提问) 加上 as const

中括号,通过索引访问类型

索引访问类型使用中括号括起来

type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"];
// type Age = number

type I1 = Person["age" | "name"];
// type I1 = string | number

type I2 = Person[keyof Person];
// type I2 = string | number | boolean

type AliveOrName = "alive" | "name";

type I3 = Person[AliveOrName];
// type I3 = string | boolean

有了 keyof 和索引访问类型,我们可以得到一个泛型 valueOf 获得对应 key 的 value 的类型

type valueOf<T> = T[keyof T]

很常见的一个应用是获取数组元素的类型

const arr = [1, 2, 3, 4, "s"];
type T = (typeof arr)[number];

// type T = string | number;