所以我尝试创建一个值对类型并得到错误消息:"无法找到名称'key'。"它是如何正常工作的?
import * as websocket from "websocket";
let wsClientsList: {[key: string]: websocket.connection};
for(key in wsClientsList){
// ^^^ TS2304: Cannot find name 'key'.
wsClientsList[key].sendUTF(message);
console.log('send Message to: ', wsClientsList[key]);
}
您需要使用var
,let
或const
声明名为key
的变量
for(let key in wsClientsList) {
wsClientsList[key].sendUTF(message);
console.log('send Message to: ', wsClientsList[key]);
}
在for in
和for of
循环中,大多数情况下可以使用const
,而不像在传统的for
循环中使用增量。