Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.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访问hashmap_Typescript_Hashmap - Fatal编程技术网

带字符串变量的Typescript访问hashmap

带字符串变量的Typescript访问hashmap,typescript,hashmap,Typescript,Hashmap,我编写了以下简单代码: const testHashMap = { hello: "Hi", test: "Hey", blabla: "Halo" } const inputFromField : string = "hello"; alert(testHashMap[inputFromField]); 但最后一行不起作用,因为它要求inputFromField将来自类型“hello”|“test”|“blabla”,而不是一般字符串,我如何坚持使用字符串?因为它

我编写了以下简单代码:

const testHashMap = {
    hello: "Hi",
    test: "Hey",
    blabla: "Halo"
}

const inputFromField : string = "hello";

alert(testHashMap[inputFromField]);

但最后一行不起作用,因为它要求inputFromField将来自类型
“hello”|“test”|“blabla”
,而不是一般字符串,我如何坚持使用字符串?因为它将来应该是用户的输入。

您可以明确声明常量的类型:

const testHashMap:Record={
你好:“你好”,
测试:“嘿”,
布拉布拉:“光环”
}
Record
{[key:string]:string}
的一种更易于阅读的形式(语法糖?)。您可以像这样编写上面的代码,其含义相同:

const testHashMap:{[key:string]:string}={
你好:“你好”,
测试:“嘿”,
布拉布拉:“光环”
}

出于好奇,您能否演示一下,如果没有
记录
界面,该如何操作?