typescript高级用法梳理
August 08, 2019
infer 最早出现在 PR 中,表示在 extends
条件语句中待推断的类型变量。
比如 2.8中内置的ReturnType可以用于提取函数类型的返回值类型
type ReturnType<T> = T extends (...args: any[]) => infer P ? P : any;
-? 将代表可选项的 ?
去掉
type Required<T> = { [P in keyof T]-?: T[P] };
类似地还可以对 readonly
进行加减.
以下代码的作用就是将 T 的所有属性的 readonly 移除,你也可以写一个相反的出来.
type Mutable<T> = {
-readonly [P in keyof T]: T[P]
}
阅读量
Written by xi ming You should follow him on Github