带有元组作为键的TypeScript字典

时间:2018-04-18 14:03:40

标签: angular typescript jasmine karma-runner

我正在为我的Angular 5应用程序在Jasmine中写一个假的,并希望存储一个假结应返回的结果字典,具体取决于传递给假冒的多个参数的值。

我认为可以在TypeScript中定义字典,使用表示伪造的参数的元组作为键,以及应该作为值返回的结果。这些方面的东西:

type FakeParams = [string, ListTypes, string];
type DictionaryItem = [FakeParams, string];
const paramsDictionary: DictionaryItem[] = [];

paramsDictionary['1046', ListTypes.DirectOwners, 'sanctions'] = '123';

不幸的是,TypeScript抱怨Left side of comma operator is unused and has no side effects。无论我在元组的第一个参数中作为123提供什么值,它都会返回结果string

有办法做到这一点吗?如果没有,除了将多个参数的值与我的假设相匹配外,我还能如何从假货中返回不同的值?

我考虑过定义一个通用字典类型,使用JSON.stringify()或类似的东西将键的值强制转换为字符串;但这似乎很臭。

PS我也尝试过:

paramsDictionary[['1046', ListTypes.DirectOwners, 'sanctions']] = '123';

但这似乎会导致TypeScript更加麻烦。

1 个答案:

答案 0 :(得分:0)

如果你真的想使用一个元组,你可以编写一个辅助类来封装Tuple-To-String转换(生成密钥)。

然后,您可以在上面的问题中使用ParamsDictionary的实例。

enum ListTypes {
    DirectOwners,
    IndirectOwners,
}

type FakeParams = [string, ListTypes, string];

class ParamsDictionary {
    private map = new Map<string, string>();

    private key(p: FakeParams) {
        return `${p[0]}-${p[1]}-${p[2]}`;
    } 

    public set(p: FakeParams, value: string) {
        const key = this.key(p);
        this.map.set(key, value);
    }

    public get(p: FakeParams) {
        const key = this.key(p);
        return this.map.get(key);
    }
}

const paramsDictionary = new ParamsDictionary();

// Set a couple parameters
paramsDictionary.set(['1046', ListTypes.DirectOwners, 'sanctions'], '123');
paramsDictionary.set(['1050', ListTypes.DirectOwners, 'sanctions'], '456');

// Get a couple parameters
console.log(paramsDictionary.get(['1046', ListTypes.DirectOwners, 'sanctions'])); // prints "123"
console.log(paramsDictionary.get(['1050', ListTypes.DirectOwners, 'sanctions'])); // prints "456"

在TypeScript Playground中试用:goo.gl/e3LBRG

相关问题