我想将 string -> string 的映射存储在 Typescript 对象中,并强制所有键映射到字符串。例如:
var stuff = {}; stuff["a"] = "foo"; // okay stuff["b"] = "bar"; // okay stuff["c"] = false; // ERROR! bool != string
有没有办法让我强制这些值必须是字符串(或任何类型..)?
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