Is key,value pair available in typescript? If yes how to do that. Can anyone provide sample example links.
-
1yes it is,can u specify your requirement ? – Taha Naqvi Apr 07 '16 at 05:36
-
typescript transpiles(not compile) into javascript, so all feature of javascript is available in typescript. e.g. if you write your code in js and change its extension to .ts, it will work as fine as your js code. learn more about it on :- https://www.typescriptlang.org/docs/. – Ajay Apr 07 '16 at 07:51
14 Answers
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
.

- 261,912
- 58
- 460
- 511
-
2This is a map or dictionary. If you want something equivalent to a C# KeyValuePair, see answer https://stackoverflow.com/questions/36467469/is-key-value-pair-available-in-typescript/50621451#50621451 – Jack Miller May 31 '18 at 09:53
-
21Also nice to know, you don't need to call it `key`. You can, for instance, also write this: `[countryCode: string]: string`. Nice for readability. – Jeff Huijsmans Dec 27 '18 at 14:47
-
2This is the updated link: https://basarat.gitbook.io/typescript/type-system/index-signatures – BornToCode Feb 11 '20 at 17:42
-
2Yes, this is a map. But every time I search for "TypeScript Map," all I get is es6 Map, which is *not* what I want! So I'm very thankful that this answer is here. – CoryCoolguy Aug 28 '20 at 04:26
-
-
-
I got it with `type Foo = { [key in CustomType]: number; } ;` but that means it needs every key but for a generic mapping, `type Foo = { CustomType: number; } ;` – Justin Jul 22 '23 at 18:24
-
`type Foo = { CustomType: number; } ;` treats `CustomType` as a string "CustomType" – Justin Jul 22 '23 at 18:30
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;
-
5This helped a lot - Less code than the interface approach because it doesn't require describing `Bar` – TheGeekZn May 07 '18 at 07:14
-
-
2indexedArray = {}; indexedArray["one"] = 1; /* good **/ indexedArray["two"] = "two"; /* fails */ – Jaime May 08 '19 at 13:08
-
1
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'}
];

- 4,929
- 1
- 33
- 25
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" };

- 6,843
- 3
- 48
- 66
-
7Somewhat funny, already 6 votes with a sum of 0. Would the downvoters mind adding a comment what is bad about this solution? – Jack Miller Aug 27 '18 at 07:10
-
15I too would like to know. Down voters never leave a comment, I sometimes think because they themselves don't know any better solution. – Ruan Sep 06 '18 at 07:38
-
I didn't downvote but this solution doesn't have add, get, remove, etc. – DaNeSh Aug 08 '19 at 17:05
-
5@DaNeSh That is right. A `KeyValuePair` is not a list, but it could be an entry of a list. Maybe you are looking for a `List<>`? See https://stackoverflow.com/questions/23096260/is-there-a-typescript-list-and-or-map-class-library – Jack Miller Aug 09 '19 at 06:09
-
How to use the key to get the value? is it like: keyValuePair["k"]? – Heisenberg Nov 21 '19 at 18:57
-
4**A ``KeyValuePair`` is not a list**. There is just a single key and a single value within. Key: `foo.key` and value: `foo.value`. It seems your are looking for a `List<>` --> https://stackoverflow.com/questions/23096260/is-there-a-typescript-list-and-or-map-class-library – Jack Miller Nov 22 '19 at 05:36
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

- 6,843
- 3
- 48
- 66
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!

- 1,053
- 16
- 31
-
-
1@JackMiller Map is defined by ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map – Randolpho Aug 09 '18 at 19:49
-
1yourVar[YourKeyType] = XXX. This does not set an element in the Map. It does set a property. – mcoolive Jun 07 '19 at 23:20
-
-
-
1
an example of a key value pair is:
[key: string]: string
you can put anything as the value, of course

- 157
- 1
- 5
-
1`export default interface KeyValuePair { [key: string]: string | number | boolean; }` Is slightly better, but is this weak typing? Does this defeat the purpose to some extent? – Arajay Sep 18 '20 at 21:26
-
Yes but when you have array of those like `newRows: { [key: string]: string; }[]` then filter wont work `this.newRows = this.newRows.filter(x=>x.length>0)` Operator '>' cannot be applied to types 'string' and 'number'.ts(2365) x is an item of the array to supposed to be an array itself. Any ideas? – Pawel Cioch Sep 02 '22 at 17:15
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:
Object
, esp.Object.entries
,Object.fromEntries
Map
, esp.Map.prototype.entries
andnew Map()
constructorSet
, esp.Set.prototype.entries

- 66,267
- 20
- 199
- 171
-
-
Just write `const kvp: KeyValuePairNamed = ["mykey", "myval"]`. The labels are a type-only construct for documentation purposes. – ford04 Jul 25 '21 at 12:21
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());

- 272
- 2
- 10
-
This is not helpfull if you're trying to type data coming from the backend. – Mathijs Segers Sep 18 '18 at 10:34
-
@MathijsSegers This class is not meant to be a concrete type. Use this class as a derived type into your concrete type – GoldBishop Mar 03 '20 at 13:31
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

- 379
- 3
- 7
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.
export declare interface KeyValue<K, V> {
key: K;
value: V;
}

- 2,869
- 2
- 22
- 23

- 113
- 1
- 5
-
-
1@fdrobidoux generally for typescript you will see, eg, `Record
` (simply replace "KeyValue" with "Record". – JimmyTheCode Aug 07 '23 at 11:50
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,
}

- 26
- 2
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

- 1,291
- 1
- 9
- 7