typescript 中的字典或 map 类型-ag捕鱼王app官网

当前位置:ag捕鱼王app官网 > > 编程语言 > >

typescript 中的字典或 map 类型

作者:迹忆客 最近更新:2023/03/19 浏览次数:

字典或 map 用于从对象中快速检索项目。typescript 没有任何 map 或字典的概念。

纯 javascript 具有可以设置和检索键值对的对象。typescript 提供 record 类型,通过纯 javascript 对象表示字典或映射。

record 类型限制在纯 javascript 对象中设置的键和值。

在 typescript 中使用 record 类型

typescript 中的 record 类型表示严格的键值对。更具体地说,record 表示对象只接受类型 k,并且对应于这些键的值应该是类型 v

record 的键将产生 k 作为类型,而 record[k] 等价于 vrecord 类型是诸如 { [ 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 中使用 partialrecord 类型

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
}

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

发布时间:2023/03/19 浏览次数:254 分类:

本教程指南通过特定的实现和编码示例深入了解了 typescript 中 declare 关键字的用途。

发布时间:2023/03/19 浏览次数:962 分类:

本篇文章演示了类的 get 和 set 属性以及如何在 typescript 中实现它。

在 typescript 中格式化日期和时间

发布时间:2023/03/19 浏览次数:269 分类:

本教程介绍内置对象 date() 并讨论在 typescript 中获取、设置和格式化日期和时间的各种方法。

在 typescript 中返回一个 promise

发布时间:2023/03/19 浏览次数:586 分类:

本教程讨论如何在 typescript 中返回正确的 promise。这将提供 typescript 中 returns promise 的完整编码示例,并完整演示每个步骤。

在 typescript 中定义函数回调的类型

发布时间:2023/03/19 浏览次数:1445 分类:

本教程说明了在 typescript 中为函数回调定义类型的ag捕鱼王app官网的解决方案。为了程序员的方便和方便,实施了不同的编码实践指南。

使用 npm 将 typescript 更新到最新版本

发布时间:2023/03/19 浏览次数:446 分类:

本教程说明了如何使用 npm 更新到最新版本的 typescript。这将为如何使用 npm 将 typescript 更新到最新版本提供完整的实际示例。

使用 jquery 和 typescript

发布时间:2023/03/19 浏览次数:246 分类:

本教程提供了使用 jquery 和 typescript 的基本理解和概念。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图