Typescript 高阶类型
- 索引类型 keyof 会提取interface中的key
class KeyCls {
name: string
age: number
}
type KeyClsExample1 = keyof KeyCls
function getParams(params: keyof KeyCls) {}
getParams('name')
getParams('age')
getParams('sex')
type Keys = 'a' | 'b'
type Obj = {
[p in Keys]: any;
}
type TExtends<T, U> = T extends U ? number : never;
type TExtendExample = TExtends<number, number | string>
type NonNullable1<T, U> = T extends U ? never : T
type NonExample = NonNullable1<null | string, null | undefined>
- Pick 英文意思挑选, 也就是从某种类型中挑选出一个或多个属性
interface Todo {
title: string
desc: string
Done: boolean
}
type TodoPreview = Pick<Todo, 'Done'>
type MyPick<T, K extends keyof T = keyof T> = {
[P in K]: T[P]
}
interface Todo {
title: string
desc: string
Done: boolean
}
const todo: Pick<Readonly<Todo>, 'title'> = {
title: '你好'
}
todo.title = '啊啊啊';
type myReadonly<T> = {
readonly [K in keyof T]: T[K]
}
type myOptional<T> = {
[K in keyof T]?: T[K]
}
- Exclude 语法: Exclude<T, U>, 返回 T 中不存在于 U 的部分
type myExclude<T, U> = T extends U ? never : T
type excludeExample = myExclude<'a' | 'b', 'a' | 'c'>
interface Todo {
title: string
desc: string
Done: boolean
}
type Partial<T> = {
[P in keyof T]?: T[P]
}
type KeyOfExample1 = Partial<Todo>
let keyofEx1: KeyOfExample1 = {
title: '1'
}
- -? 将可选项代表的 ?去掉, 将该类型变成必选项, 与之对应的还有一个+?,是将可选项变成必选项
interface Todo {
title: string
desc: string
Done: boolean
}
type Mutable<T> = {
-readonly [P in keyof T]: T[P]
}
type mutableExample = Mutable<Readonly<Todo>>
// 将Todo变成可读之后再变成可写
type Required<T> = {
[P in keyof T]-?: T[P]
}
class KeyCls {
name?: string;
age?: number;
}
const requiredExample: Required<KeyCls> = {
name: "John",
} // 报错
const requiredExample2: Required<KeyCls> = {
name: "John",
age: 20,
} // 正常
- Record<K, T> 将K中所有的属性转化为T类型
type myRecord<K extends keyof any, T> = {
[P in K]: T
}
enum Methods {
GET = "get",
POST = "post",
DELETE = "delete",
PUT = "put",
}
type IRouter = myRecord<Methods, (req: any, res: any) => void>
class KeyCls {
name: string;
age: number;
}
type myOmit<T, K extends keyof T> = Pick<T, 'age'>
type myOmit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
type myOmitExample = myOmit<KeyCls, "name">;
- NonNullable:作用是去掉 T 中的 null 和 undefined。T 为字面量/具体类型的联合类型
// 4.8版本之前
type NonNullable<T> = T extends null | undefined ? never : T;
// 4.8版本之后
type NonNullable<T> = T & {}
- infer 可以推荐一个类型变量, 相当于生命一个类型变量, 这个变量的类型取决于传入的泛型T
type F<T> = T extends () => infer R ? R : T;
type F1 = F<string>
type TObj<T> = T extends { name: infer V, age: infer U } ? V : T
type TObjExample2 = TObj<{
name: number;
age: string;
}>;
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
functin getUser() {
return {
name: 'xxx',
age: 20
}
}
type GetUserType = typeof getUser;
type ReturnUser = ReturnType<GetUserType>
type ReturnUser = {