小编典典

强制 Typescript 对象的索引成员的类型?

all

我想将 string -> string 的映射存储在 Typescript 对象中,并强制所有键映射到字符串。例如:

var stuff = {};
stuff["a"] = "foo";   // okay
stuff["b"] = "bar";   // okay
stuff["c"] = false;   // ERROR!  bool != string

有没有办法让我强制这些值必须是字符串(或任何类型..)?


阅读 121

收藏
2022-03-13

共1个答案

小编典典

var stuff: { [key: string]: string; } = {};
stuff['a'] = ''; // ok
stuff['a'] = 4;  // error

// ... or, if you're using this a lot and don't want to type so much ...
interface StringMap { [key: string]: string; }
var stuff2: StringMap = { };
// same as above
2022-03-13