CodeHunter
CodeHunter

Reputation: 3923

Is key-value pair available in TypeScript?

Is key-value pair available in TypeScript? If so, how do I do that? Can anyone provide sample, example, or links?

Upvotes: 383

Views: 676798

Answers (14)

muthu raja
muthu raja

Reputation: 26

const YAHOO = 'YAHOO';
const GOOGLE = 'GOOGLE';
const google = 'google';
const yahoo = 'yahoo';

type DomainKeyType = typeof GMAIL | typeof GOOGLE;
type DomainValueType = typeof google | typeof yahoo;

type DomainType = Record<DomainKeyType , DomainValueType>

const domain: DomainType = {
  YAHOO: yahoo,
  GOOGLE: google,
}

Upvotes: 0

Besufekad Tamiru
Besufekad Tamiru

Reputation: 126

One can also simple use Record

type Foo = Record<string, number>

Further usage in the docs

Upvotes: 5

basarat
basarat

Reputation: 275847

Is key-value pair available in Typescript?

Yes. Called an index signature:

interface Foo {
   [key: string]: number;
}


let foo:Foo = {};
foo['hello'] = 123;
foo = {
  'leet': 1337
};
console.log(foo['leet']); // 1337

Here keys are string and values are number.

More

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

Upvotes: 549

Salma Tofaily
Salma Tofaily

Reputation: 153

KeyValue interface exists in angular library that uses typescript. So you have this generic interface to use if your project is angular. Or you can use its declaration to get a nice generic KeyValue interface if you are not using TS in angular.

enter image description here

export declare interface KeyValue<K, V> {
    key: K;
    value: V;
}

Upvotes: 3

ford04
ford04

Reputation: 74500

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

const keyVal: [string, string] =  ["key", "value"] // explicit type
const keyVal2 = ["key", "value"] as const // inferred type with const assertion
const [key, val] = ["key", "val"] // usage with array destructuring

You can create a generic KeyValuePair type for reusability:

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

TS 4.0

provides labeled tuple elements for better documentation and tooling support:

type KeyValuePairNamed = [key: string, value: string] // "key" and "value" labels

Compatibility

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

Playground

Upvotes: 14

Nasir Siraj
Nasir Siraj

Reputation: 439

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

Upvotes: 1

Vinayak V Naik
Vinayak V Naik

Reputation: 1351

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

Upvotes: -1

carolopolo
carolopolo

Reputation: 157

an example of a key value pair is:

[key: string]: string

you can put anything as the value, of course

Upvotes: 13

Jaime
Jaime

Reputation: 5965

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;

Upvotes: 260

magikMaker
magikMaker

Reputation: 5607

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'}
];

Upvotes: 76

HgMs
HgMs

Reputation: 282

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());

Upvotes: 4

Jack Miller
Jack Miller

Reputation: 7657

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

Upvotes: 20

Jack Miller
Jack Miller

Reputation: 7657

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

Upvotes: 42

peter70
peter70

Reputation: 1113

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!

Upvotes: 19

Related Questions