我有一个TypeScript 2.0项目,我希望使用Immutable.js
定义一个不可变的 Map 。特别地,我想将Map的键限制为已知的集合;如下所示:
type ConstrainedKeys = 'foo' | 'bar' | 'baz';
interface INameValuePair {
name: string;
value: string;
};
const dictionary = Immutable.Map<ConstrainedKeys, NameValuePair>(response);
response
可能类似于:
{
foo: {
name: 'foo',
value: 'typing is fun'
}
}
但是当我尝试引用dictionary.foo.value
时,我收到了Typescript错误:
[ts]财产&#39; foo&#39;类型&#39; Map&lt; ConstrainedKeys,INameValuePair&gt;&#39;上不存在。
答案 0 :(得分:1)
Immutable.Map
个实例没有条目属性,您需要像这样访问它们:
let foo = dictionary.get("foo");
如果您希望能够像dictionary.foo
那样访问它,那么您需要自己更改实例,或者您可以使用Proxy:
const map = Immutable.Map<ConstrainedKeys, INameValuePair>({
foo: {
name: 'foo',
value: 'typing is fun'
}
});
const dictionary = new Proxy(map, {
get: (target: Immutable.Map<ConstrainedKeys, INameValuePair>, name: ConstrainedKeys) => {
if ((target as any)[name]) {
return (target as any)[name];
}
return target.get(name);
}
}) as Immutable.Map<ConstrainedKeys, INameValuePair> & { foo: INameValuePair };
console.log(dictionary.foo); // {name: "foo", value: "typing is fun"}
console.log(dictionary.get("foo")); // {name: "foo", value: "typing is fun"}