使用TypeScript键入受约束的字典

时间:2016-10-27 10:23:58

标签: javascript typescript immutable.js

我有一个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;上不存在。

1 个答案:

答案 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"}