Grant Curell
Grant Curell

Reputation: 1763

How to create a list of dictionaries in typescript?

Intuitively, one would try something like:

interface Port_Mapping {
  number: Port_role
}
port_mappings: Port_Mapping[{number: Port_role}] = [];

where Port_role is an interface and number is an integer key. However this is met with:

Type '{ number: Port_role; }' cannot be used as an index type.

Then one might try to change to:

interface Port_Mapping {
  number: Port_role
}

port_mappings: Port_Mapping[] = [];

this.port_mappings.push({5: Port_role.input})

However this doesn't work either because number in the interface is actually a name not a type and you end up with:

Argument of type '{ 5: Port_role; }' is not assignable to parameter of type 'Port_Mapping'. Object literal may only specify known properties, and '5' does not exist in type 'Port_Mapping'.

In my case, I want a list of dictionaries where each dictionary is of the form:

[{key1: value1, key2: value2, key3: value3}]

Upvotes: 0

Views: 7695

Answers (2)

Vladi Pavelka
Vladi Pavelka

Reputation: 926

Try

interface Port_Mapping {
  [index: number]: Port_role
}

The [index: number] is an indexer - can be used only in interfaces, and means you can index the object instance using it.

Your first try doesn't make much sense in TS, you are declaring a variable port_mappings to be of type Port_Mapping indexed with an object instance {number: Port_role}, where the value of the number property is the interface type Port_role.

In the second try you are trying to push an object instance {5: Port_role.input} into an array of type Port_Mapping. There you get an obvious type missmatch, as the object instance you are pushing has no number property (and the type of array you are pushing into (Port_Mapping) has no property named "5").

Usage:

interface Dict {
  [idx: number]: string
}

const i = 5;
const dict: Dict = { 1: 'abc', [2]: 'def', [i]: 'ghi' };
dict[7] = 'jkl';
dict[i] = 'mno';
delete dict[2]; // removes the index 2: 'def' entry

const listOfDict: Dict[] = [dict, { 1: 'a', [2]: 'b', [i]: 'c'}];
listOfDict.push({ 1: 'a', [2]: 'b', [i]: 'c'});

Upvotes: 2

Alexander
Alexander

Reputation: 3247

You can use a TypeScript Record https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt

Upvotes: 0

Related Questions