TypeScript 中的字典或 map 类型
字典或 map 用于从对象中快速检索项目。TypeScript 没有任何 map 或字典的概念。
纯 JavaScript 具有可以设置和检索键值对的对象。TypeScript 提供 Record 类型,通过纯 JavaScript 对象表示字典或映射。
Record 类型限制在纯 JavaScript 对象中设置的键和值。
在 TypeScript 中使用 Record 类型
TypeScript 中的 Record 类型表示严格的键值对。更具体地说,Record<K,V> 表示对象只接受类型 K,并且对应于这些键的值应该是类型 V。
Record<K,V> 的键将产生 K 作为类型,而 Record<K,V>[K] 等价于 V。Record 类型是诸如 { [ key : K] : V } 之类的索引签名的别名。
以下代码段显示了 TypeScript 中使用的等效索引签名类型和 Record 类型结构。
enum Level {
info = "info",
warning = "warning",
danger = "danger",
fatal = "fatal"
}
type LevelStrings = keyof typeof Level;
var bannerMessageInfo : Record<LevelStrings, string> = {
info : "[INFO]",
warning : "[WARNING]" ,
danger : "[DANGER]",
fatal : "[FATAL]"
};
function generateLogMessage(message : string , level : LevelStrings){
console.log(bannerMessageInfo[level] + " : " + message);
}
generateLogMessage("This is how Record Type can be used.", Level.info);
输出:
"[INFO] : This is how Record Type can be used."
上述 Record 类型也可以表示为索引签名。
type BannerTypeMap = {
[level in LevelStrings] : string;
}
var bannerMessageInfo : BannerTypeMap = {
info : "[INFO]",
warning : "[WARNING]" ,
danger : "[DANGER]",
fatal : "[FATAL]"
};
BannerTypeMap 是 TypeScript 中的 Mapped Type 对象,在这里用作索引签名并在 bannerMessageInfo 中生成所有类型的消息。
在上面的示例中,映射中的所有字段都是必需的,否则 TypeScript 可能无法编译。部分类型可以与 Record 类型一起使用以创建更强大的类型。
在 TypeScript 中使用 Partial 和 Record 类型
Partial 关键字可以用一些传递的属性覆盖一些初始默认属性。下面的代码段演示了这一点。
type PropStrings = 'height' | 'width' | 'shadow' ;
type Props = Record<PropStrings , number>
function CombineProps(props : Partial<Props> ){
var initProps : Props = {
height : 10,
width : 20,
shadow : 4
};
var finalProps = {...initProps , ...props};
console.log(finalProps);
}
CombineProps({width : 40});
输出:
{
"height": 10,
"width": 40,
"shadow": 4
}
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
