TypeScript 高级用法 -- Record 作者: Chuwen 时间: 2022-02-07 分类: TypeScript 这里仅作为个人记录? 不做详细解析 我对 TS 不是特别了解,所以无法表达出,但是这种情况很多人应该会遇到过 相关资料参考: - https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeystype - https://juejin.cn/post/6844904066489778183 - https://www.jianshu.com/p/ff5ee22b2053 ### 会报出警告的代码: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Student'. No index signature with a parameter of type 'string' was found on type 'Student'. > TS7053:元素隐式具有“any”类型,因为“字符串”类型的表达式不能用于索引“Student”类型。 在Student学生”类型上找不到具有“string”类型参数的索引签名。 ```ts export interface IStudentClass { student?: Student updatedStudentInfo(key: string, val: string): void } export type Student = { name: string age: number birth: { year: number month: number } } class StudentClass implements IStudentClass { student?: Student updatedStudentInfo(key: string, val: string) { this.student && this.student[key] && (this.student[key] = val) } } ``` ![TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Student'. No index signature with a parameter of type 'string' was found on type 'Student'.](https://cdn.nowtime.cc/2022/02/07/1024976837.png) --- ### 使用 `Record` : 一切正常 ```ts export type Student = { name: string age: number birth: { year: number month: number } } export interface IStudentClass { student?: Record /** * 更新学生信息 * @param key * @param val */ updatedStudentInfo(key: K, val: Student[K]): void } class StudentClass implements IStudentClass { student?: Record updatedStudentInfo(key: K, val: Student[K]): void { this.student && this.student.hasOwnProperty(key) && (this.student[key] = val) } } ``` ![](https://cdn.nowtime.cc/2022/02/07/1776462821.png) 标签: TypeScript, Record