typescript 类型Record

116 阅读1分钟

Record<keys, type>

构造一个对象类型,其属性key是Keys,属性的value是Type。被用于映射一个类型的属性到另一个类型。

简单来说,TypeScript中的Record可以实现定义一个对象的key和value类型,Record 后面的泛型就是对象键和值的类型。

源码

/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};

Record常用的格式如下:

type proxyKType = Record<K,T>

这里会将K中的所有属性值都转换为T类型,并将返回的新类型返回给proxyKType,K可以是联合类型、对象、枚举…

实例

// demo1
type petsGroup = 'dog' | 'cat' | 'fish';
interface IPetInfo {
    name: string;
    age: number;
}

type IPets = Record<petsGroup, IPetInfo>;

const animalsInfo:IPets = {
    dog:{
        name:'dogName',
        age:2
    },
    cat:{
        name:'catName',
        age:3
    },
    fish:{
        name:'fishName',
        age:5
    }
}
// demo2
interface Staff {
  name:string,
  salary:number,
}
  
 type StaffJson = Record<keyof Staff, string>

  const product: StaffJson = {
    name: 'John',
    salary:'3000'
  }