1. keyof ,类型索引的使用
keyof
类似于 Object.keys
,用于获取一个接口中 Key 的联合类型
interface Button {
type: string
text: string
}
type ButtonKeys = keyof Button
// 等效于
type ButtonKeys = "type" | "text"
type Kin = keyof any
//等效于
type Kin = string | number | symbol
2.extends,对泛型进行类型约束
type BaseType = string | number | boolean
// 这里表示 copy 的参数
// 只能是字符串、数字、布尔这几种基础类型
function copy<T extends BaseType>(arg: T): T {
return arg
}
extends
经常与 keyof
一起使用,例如我们有一个方法专门用来获取对象的值,但是这个对象并不确定,我们就可以使用 extends
和 keyof
进行约束
function getValue<T, K extends keyof T>(obj: T, key: K) {
return obj[key]
}
const obj = { a: 1 }
const a = getValue(obj, 'a')
3. Partial, 将一个接口的所有属性变成可选的
type Partial<T> = {
[P in keyof T]?: T[P]|undefin
}
interface Cat{
nick:string
color:string
}
const c1: Cat={
nick:'tom',
color:'grey'
}
const c2: Partial<Cat>={
}
4.Required,将一个接口的属性全部变成必选
type Required<T> = { [P in keyof T]-?: T[P]; }
interface Cat{
nick?:string
color?:string
}
const c1: Cat={
}
const c2: Required<Cat>={
nick:'tom',
color:'grey'
}
5.Recorde ,构造一个对象类型
它的属性键是K,属性值类型是T
type Record<K extends string | number | symbol, T> = { [P in K]: T; }
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
6.Pick<Type, Keys>,提取接口的属性生成一个新的类型
type Pick<T, K extends keyof T> = {
[P in K]: T[P]
}
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
7.Extract<Type, Union> 构造一个Type和Union交集的新类型
type Extract<T, U> = T extends U ? T : never
type T0 = Extract<"a" | "b" | "c", "a" |"b" |"f">;
const t:T0 = 'a' //a或b
8.Exclude<UnionType, ExcludedMembers> 与Extract相反,排除交集,构造一个新类型
type Exclude<T, U> = T extends U ? never : T
type T0 = Exclude<"a" | "b" | "c", "a">;
// type T0 = "b" | "c"
9.Omit<Type, Keys>,与Pick相反,去除Types类型中的keys,构造一个新类型
type Omit<T, K extends string | number | symbol> = {
[P in Exclude<keyof T, K>]: T[P];
}
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};
10.ReturnType<Type>,构造一个函数返回值类型
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any
type T0 = ReturnType<() => string>; //string
function f1 ():{a:number,b:string}{
return {
a:1,
b:'2'
}
}
type T4 = ReturnType<typeof f1>;
type T4 = {
a: number;
b: string;
}
11.InstanceType<Type>,构造由 Type 中构造函数的实例类型组成的类型。
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any
class C {
x = 0;
y = 0;
}
type T0 = InstanceType<typeof C>;
const a:T0 = {
x:1,
y:2
}