Is key-value pair available in Typescript?
TypescriptTypescript Problem Overview
Is key,value pair available in typescript? If yes how to do that. Can anyone provide sample example links.
Typescript Solutions
Solution 1 - Typescript
> 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
.
Solution 2 - Typescript
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;
Solution 3 - Typescript
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'}];
Solution 4 - Typescript
> 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" };
Solution 5 - Typescript
Not for the questioner, but for all others, which are interested: See: https://stackoverflow.com/questions/40976536/how-to-define-typescript-map-of-key-value-pair-where-key-is-a-number-and-value
The solution is therefore:
let yourVar: Map<YourKeyType, YourValueType>;
// now you can use it:
yourVar = new Map<YourKeyType, YourValueType>();
yourVar[YourKeyType] = <YourValueType> yourValue;
Cheers!
Solution 6 - Typescript
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
Solution 7 - Typescript
an example of a key value pair is:
[key: string]: string
you can put anything as the value, of course
Solution 8 - Typescript
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
Solution 9 - Typescript
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());
Solution 10 - Typescript
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;
}
Solution 11 - Typescript
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
Solution 12 - Typescript
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