企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
>[success] # Record -- 一组属性 K(类型 T) ~~~ 1.Record 有两个参数指定key,和key 对应value 值类型 ~~~ >[danger] ##### 源码 ~~~ type Record<K extends keyof any, T> = { [P in K]: T; }; ~~~ >[danger] ##### 案例 ~~~ // 错误用有时候工作,定义了一个对象类型赋值是一个object // object 没有foo字段会报错 // let bb: object = { // foo: 's', // } // bb.foo // k 为任意类型 ,value 为任意类型,解决 let aa: Record<any, any> = { foo: 'w', } aa.foo ~~~ >[danger] ##### 案例 ~~~ interface Info { name:string, age:number } // 定义的a key 是Info 接口Key类型,value 是string类型 const a:Record<Info[keyof Info],string> = { name:'w', age:'w' } ~~~ >[danger] ##### 案例 ~~~ function mapObject<K extends string | number, T, U>(obj: Record<K, T>, f: (x: T) => U): Record<K, U> { const res: any = {} for (const key in obj) { res[key] = f(obj[key]) } return res } const names = { 0: 'hello', 1: 'world', 2: 'bye' } const lengths = mapObject(names, (s) => s.length) console.log(lengths) ~~~ >[danger] ##### 案例 ~~~ type MenuKey = 'home' | 'about' | 'more'; interface Menu { label: string; hidden?: boolean; } const menus: Record<MenuKey, Menu> = { about: { label: '关于' }, home: { label: '主页' }, more: { label: '更多', hidden: true }, }; ~~~ >[danger] ##### 案例 ~~~ import { IncomingMessage, ServerResponse } from "http"; enum Methods { GET = "get", POST = "post", DELETE = "delete", PUT = "put", } type IRouter = Record<Methods, (req: IncomingMessage, res: ServerResponse) => void>; ~~~ ![](https://img.kancloud.cn/69/7c/697cda72865af40c0ec7f52fef9c2487_846x307.png)