typescript 类型映射 (ReadOnly、Partial)
有时候需要一个类型,是依赖于上一个类型但是,对属性的要求去不同 interface Person{ name: string; agent: number; } type Person2 = Readonly<Person>; type Person3 = Partial<Person>; class Test { run() { let person: Person = { name: 'dd', agent: 1 }; person.name = 'cc'; let person2: Person2 = { name: 'read', agent: 1 }; // person2.agent = 3; 报错 let person3: Person3 = { name: 'person 3' // 属性不完整也不会报错 } } } ReadOnly、Partial源码 type Readonly<T> = { readonly [P in keyof T]: T[P]; } type Partial<T> = { [P in keyof T]?: T[P]; } 用 in, keyof即可实现 type Pick<T, K extends keyof T> = { [P in K]: T[P]; } type Record<K extends string, T> = { [P in K]: T; }