TypeScript里的Index signature
参考链接:https://basarat.gitbook.io/typescript/type-system/index-signatures
看一个例子:
class Foo {constructor(public message: string){};log(){console.log(this.message)}}let foo: any = {};foo['Hello'] = new Foo('World');foo['Hello'].log(); // Worldconsole.log(c);
最后输出World
如果把一个对象作为key,结果会怎么样?JavaScript会自动调用该对象的toString实现,将结果作为key来访问。
let obj = {toString(){console.log('toString called')
return 'Hello'
}
}
let foo: any = {};
foo[obj] = 'World'; // toString called
console.log(foo[obj]); // toString called, World
console.log(foo['Hello']); // World
而在TypeScript里,无法通过编译:TS2538: Type ‘{ toString(): string; }’ cannot be used as an index type.
除非显式调用toString方法:
测试结果:
结论1:TypeScript index signatures must be either string or number
看个例子:
let foo2:{ [index:string] : {message: string} } = {};
foo2是一个对象,包含了一个index signature,类型为字符串。名称可以任意取,该index指向另一个对象,该对象必须包含一个字段message,值为string.
下列代码会引起编译错误:
更多Jerry的原创文章,尽在:“汪子熙”:
TypeScript里的Index signature相关推荐
- 什么是 TypeScript 里的 Constructor signature
TypeScript 官方文档里关于 Constructor signature 只有这短短的一段话: JavaScript functions can also be invoked with th ...
- Typescript ques:An index signature parameter type cannot be a union type. Consider using a mapped...
写接口类型时,希望一个类型的键值是联合类型中固定的几个 const enum MSGTYPE{TEXT = 'text',IMAGE = 'image', } // or // type MSGTYP ...
- thinkphp url去掉index.php,thinkphp 去掉URL 里面的index.php(?s=)
例如你的原路径是 http://localhost/test/index.php/home/goods/index.html 那么现在的地址是 http://localhost/test/home/g ...
- TypeScript 里 interface 和 type 的区别
StackOverflow 上的讨论链接 Interface vs Type alias in TypeScript 2.7 Differences Between Type Aliases and ...
- TypeScript里一些特殊的类型
本文内容部分来自:https://www.w3cschool.cn/typescript/typescript-basic-types.html any 有时候,我们会想要为那些在编程阶段还不清楚类型 ...
- TypeScript里string和String,真不是仅仅是大小写的区别
本文分享自华为云社区<TypeScript里string和String的区别>,作者:gentle_zhou . 背景 与JavaScript语言不同的是,TypeScript使用的是静态 ...
- TypeScript里的工具类型Partial的理解用法
TypeScript里的工具类型Partial的理解用法 Partial 可以快速把某个接口类型中定义的属性类型变成可选的(Optional): 其实Partial源码很简单 Partial 可以快速 ...
- 打开wordpress里的index.php文件
这里默认已经装好了phpstudy这个集成开发环境了,然后打开大概就是下面的这个界面. 为何上面说的是"大概"呢?对的,或许你们的和我现在这个界面有一点不一样的地方,就是php的版 ...
- tp6隐藏省略去掉url里的index.php路由前缀
tp6隐藏省略去掉url里的index.php路由前缀方法 修改TP6框架public中.htaccess文件 <IfModule mod_rewrite.c>Options +Follo ...
最新文章
- python的垃圾回收机制和析构函数__del__
- python循环顶帖_设计Python数据库连接池1-对象的循环引用问题
- docker 主进程 日志_运维笔记--docker高效查看后台日志
- python模块介绍-asyncore 异步socket处理器
- 我最喜欢的二十句名言
- 如何在C ++中使用std :: getline()?
- Java 实现视频下载功能
- abaqus14安装_Abaqus安装方法
- matlab的yalmip为什么这么慢,Yalmip使用学习
- iOS 开发者常用的75 个工具
- xml的三种解析方法
- 抖音seo源码二次开发 抖音seo源码二次开发
- 【winRAR去广告弹窗】
- 【转载】秦九韶算法 Horner算法
- PS如何快速完整的抠头发丝,请看详细的教程
- 高维空间中点到超平面的距离
- 逻辑思维能力选择题30道
- 智子观测宣布和数榜签约合作,强化大数据采集技术
- python绘制气象等值线图_用Matplotlib绘制Python等值线图
- C# 在Windows系统下使用蓝牙进行数据通讯