在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
有时候需要一个类型,是依赖于上一个类型但是,对属性的要求去不同 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; }
|
请发表评论