2017-01-22 31 views
2

在使用WebSockets的應用程序中,我想將套接字關閉代碼映射到字符串,以便在關閉事件時,我可以從數字代碼中獲取消息。目前,我只是從一個「常量」模塊導出對象,像這樣:TypeScript:如何創建只讀數字索引對象

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] = "garbage"CloseCodes[1234]="hello"delete(CloseCodes[event.code]),所有這些都是不希望的。有沒有辦法爲這種類型的用法創建只讀數字索引結構?我正在尋找一種TypeScript方式來做到這一點,而不是ES6 Object.defineProperty(...)的方式。

回答

1

是的,只要用readonly index signature聲明它:

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! 

我相信如上圖所示打字稿2.0中引入的方式使用readonly,所以你需要使用至少該版本打字稿的。另請注意,不允許刪除運算符was a very recent TypeScript change,所以您可能在您的項目中看不到此行爲。

+0

謝謝,這個作品。我沒有遇到'刪除WsCloseCodes [1000];'的錯誤;'但是,不知道爲什麼因爲我運行的是TypeScript 2.1.4。無論哪種方式,這是我正在尋找。 – 4EverLive