Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TypeScript:如何创建只读数字索引对象_Typescript_Indexing_Readonly - Fatal编程技术网

TypeScript:如何创建只读数字索引对象

TypeScript:如何创建只读数字索引对象,typescript,indexing,readonly,Typescript,Indexing,Readonly,在使用WebSockets的应用程序中,我希望将套接字关闭代码映射到字符串,以便在关闭事件中,我可以从数字代码中获取消息。目前,我只是从“常量”模块导出一个对象,如下所示: export const CloseCodes: { [index: number]: string } = { 1000: "Normal closure", 1001: "The endpoint is going away", 1002: "The endpoint is terminating

在使用WebSockets的应用程序中,我希望将套接字关闭代码映射到字符串,以便在关闭事件中,我可以从数字代码中获取消息。目前,我只是从“常量”模块导出一个对象,如下所示:

export const CloseCodes: { [index: number]: string } = {
    1000: "Normal closure",
    1001: "The endpoint is going away",
    1002: "The endpoint is terminating"
    // etc.
}

在套接字关闭时,我可以通过
CloseCodes[event.code]
event.code
映射到字符串,这是我想要的,但我也可以执行
CloseCodes[event.code]=“垃圾”
CloseCodes[1234]=“hello”
delete(CloseCodes[event.code])
,所有这些都是不需要的。有没有办法为这种用法创建只读数字索引结构?我正在寻找一种实现这一点的TypeScript方法,而不是ES6
对象。defineProperty(…)
方法。

是的,只需用一个:


我相信在TypeScript 2.0中引入了以上面所示的方式使用
readonly
,因此您至少需要使用该版本的TypeScript。另外请注意,不允许使用delete操作符,因此您可能在项目中还没有看到这种行为。

谢谢,这很有效。我没有在删除WsCloseCodes[1000]时遇到错误虽然,不知道为什么,因为我运行的是TypeScript 2.1.4。不管怎样,这就是我要找的。
export const CloseCodes: { readonly [index: number]: string } = {
    1000: "Normal closure",
    1001: "The endpoint is going away",
    1002: "The endpoint is terminating"
    // etc.
}

// Both "Index signature in type '{ readonly [index: number]: string; }' only permits reading." errors:
CloseCodes[1000] = "bad";  // error!
delete CloseCodes[1000];  // error!