用TypeScript输入一个约束字典

Typing a constrained dictionary with TypeScript

本文关键字:一个 约束 字典 TypeScript 输入      更新时间:2023-09-26

我有一个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]属性'foo'在类型'Map<ConstrainedKeys,INameValuePair>'上不存在。

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