Use an index signature to define a key-value pair in TypeScript, e.g. const employee: { [key: string]: string | number } = {} . An index signature is used when we don't know all the names of a type's keys ahead of time, but we know the shape of their values. Copied!
A key-value pair (KVP) is an abstract data type that includes a group of key identifiers and a set of associated values. Key-value pairs are frequently used in lookup tables, hash tables and configuration files.
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
.
You can use an es6 Map
for proper dictionaries, polyfilled by core-js
.
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;
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'}
];
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" };
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With