Record<K,T>构造具有给定类型T的一组属性K的类型。

从使用上看可以类比为C# 的 Dictionary<TKey,TValue>


为什么要使用这个?

看下面的代码

var maps = {
    'wcIndex': 'tabHome',
    'wcRight': 'tabRights',
    'wcAddress': 'tabShops',
    'wcMember': 'tabUser'
};
// 如果是ts,这里会报错
// 元素隐式具有 "any" 类型,因为类型为 "any" 的表达式不能用于索引类型
var tabName = maps[options.m];

这个时候,你可以使用Record来指定值的类型

var maps: Record<string, string> = {
  'wcIndex': 'tabHome',
  'wcRight': 'tabRights',
  'wcAddress': 'tabShops',
  'wcMember': 'tabUser'
};
var tabName = maps[options.m];


更多使用示例

限定键的取值

type Ingredient = "chocolate" | "peanuts" | "cocoa" | "marshmallow" | "cherry";

export const ingredients: Record<Ingredient, string> = {
  chocolate: "Chocolate",
  cocoa: "Cocoa Powder",
  cherry: "Cherry",
  marshmallow: "Marshmallow",
  peanuts: "Peanut Butter",
};

追加额外的键

type Ingredient = "chocolate" | "peanuts" | "cocoa" | "marshmallow" | "cherry";

export const ingredients: Record<Ingredient | "apple", string> = {
  chocolate: "Chocolate",
  cocoa: "Cocoa Powder",
  cherry: "Cherry",
  marshmallow: "Marshmallow",
  peanuts: "Peanut Butter",
  apple: "Apple"
};