kd-cloud-web / Blog

一群人, 关于前端, 做一些有趣的事儿
13 stars 1 forks source link

typescript 操作符 #63

Open zzkkui opened 3 years ago

zzkkui commented 3 years ago

typescript 操作符

操作符

extends 条件类型

T extends U ? X : Y

上面的类型表示何时T可分配给U类型为X,否则类型为Y。

typeof

用来获取一个变量声明或者对象的类型

interface Person {
  name: string;
  age: number;
}

const sem: Person = { name: 'semlinker', age: 30 };
type Sem= typeof sem; // -> Person

function toArray(x: number): Array<number> {
  return [x];
}

type Func = typeof toArray; // -> (x: number) => number[]

keyof

用于获取某种类型的所有键,其返回类型是联合类型。

interface Person {
  name: string;
  age: number;
  location: string;
}

type K1 = keyof Person; // "name" | "age" | "location"
type K2 = keyof Person[];  // number | "length" | "push" | "concat" | ...
type K3 = keyof { [x: string]: Person };  // string | number

in

用来遍历枚举类型

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

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

infer

在条件类型表达式 T extends U ? X : Y 中,我们可以用 infer 声明(推断)一个类型变量并且对它进行使用。

demo

// infer P 表示待推断的函数参数。
// 如果 T 能赋值给 (param: infer P) => any,则结果是 (param: infer P) => any 类型中的参数 P,否则返回为 T。
type ParamType<T> = T extends (param: infer P) => any ? P : T;

interface User {
  name: string;
  age: number;
}

type Func = (user: User) => void;

type Param = ParamType<Func>; // Param = User
type AA = ParamType<string>; // string

ReturnType 中的 infer

type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

根据 extends 可知道这里的作用:如果传入的类型 T 能够赋值给 (...args: any) => R 则返回类型 R。
但是这里的 R 外部并没有指定

Hibop commented 3 years ago

👏 👏 👏