[typescript] Is key-value pair available in Typescript?

Is key,value pair available in typescript? If yes how to do that. Can anyone provide sample example links.

This question is related to typescript

The answer is


class Pair<T1, T2> {
    private key: T1;
    private value: T2;

    constructor(key: T1, value: T2) {
        this.key = key;
        this.value = value;
    }

    getKey() {
        return this.key;
    }

    getValue() {
        return this.value;
    }
}
const myPair = new Pair<string, number>('test', 123);
console.log(myPair.getKey(), myPair.getValue());

The simplest way would be something like:

var indexedArray: {[key: string]: number}

Usage:

var indexedArray: {[key: string]: number} = {
    foo: 2118,
    bar: 2118
}

indexedArray['foo'] = 2118;
indexedArray.foo= 2118;

let foo = indexedArray['myKey'];
let bar = indexedArray.myKey;

Is key-value pair available in Typescript?

If you think of a C# KeyValuePair<string, string>: No, but you can easily define one yourself:

interface KeyValuePair {
    key: string;
    value: string;
}

Usage:

let foo: KeyValuePair = { key: "k", value: "val" };

TypeScript has Map. You can use like:

public myMap = new Map<K,V>([
[k1, v1],
[k2, v2]
]);

myMap.get(key); // returns value
myMap.set(key, value); // import a new data
myMap.has(key); // check data


an example of a key value pair is:

[key: string]: string

you can put anything as the value, of course


Another simple way is to use a tuple:

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10];
// Access elements
console.log("First: " + x["0"] + " Second: " + x["1"]);

Output:

First: hello Second: 10


Is key-value pair available in Typescript?

Yes. Called an index signature:

interface Foo {
   [key: string]: Bar;
} 
let foo:Foo = {};

Here keys are string and values are Bar.

More

You can use an es6 Map for proper dictionaries, polyfilled by core-js.


A concise way is to use a tuple as key-value pair:

const keyVal: [string, string] =  ["key", "value"] // explicit type
// or
const keyVal2 = ["key", "value"] as const // inferred type with const assertion

[key, value] tuples also ensure compatibility to JS built-in objects:

You can create a generic KeyValuePair type for reusability:

type KeyValuePair<K extends string | number, V = unknown> = [K, V]
const kv: KeyValuePair<string, string> = ["key", "value"]

TS 4.0: Named tuples

Upcoming TS 4.0 provides named/labeled tuples for better documentation and tooling support:

type KeyValuePairNamed = [key: string, value: string] // add `key` and `value` labels
const [key, val]: KeyValuePairNamed = ["key", "val"] // array destructuring for convenience

Working playground example


Not for the questioner, but for all others, which are interested: See: How to define Typescript Map of key value pair. where key is a number and value is an array of objects

The solution is therefore:

let yourVar: Map<YourKeyType, YourValueType>;
// now you can use it:
yourVar = new Map<YourKeyType, YourValueType>();
yourVar[YourKeyType] = <YourValueType> yourValue;

Cheers!


You can also consider using Record, like this:

const someArray: Record<string, string>[] = [
    {'first': 'one'},
    {'second': 'two'}
];

Or write something like this:

const someArray: {key: string, value: string}[] = [
    {key: 'first', value: 'one'},
    {key: 'second', value: 'two'}
];

If you are trying to use below example

Example: { value1: "value1" }

And add conditionalData dynamically based on some condition, Try

let dataToWrite: any = {value1: "value1"};

if(conditionalData)
   dataToWrite["conditionalData"] = conditionalData