我有一个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时,我会得到类型记录错误:
ts属性'foo‘在'Map’类型上不存在。
发布于 2016-10-27 10:53:20
Immutable.Map实例没有条目的属性,您需要按如下方式访问它们:
let foo = dictionary.get("foo");如果您希望能够像dictionary.foo一样访问它,那么您需要自己更改实例,或者可以使用代理
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"}https://stackoverflow.com/questions/40282167
复制相似问题