Is key-value pair available in TypeScript? If so, how do I do that? Can anyone provide sample, example, or links?
-
1yes it is,can u specify your requirement ?Taha Naqvi– Taha Naqvi2016-04-07 05:36:39 +00:00Commented Apr 7, 2016 at 5: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 :- typescriptlang.org/docs.Ajay– Ajay2016-04-07 07:51:21 +00:00Commented Apr 7, 2016 at 7: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.
7 Comments
key. You can, for instance, also write this: [countryCode: string]: string. Nice for readability.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;
4 Comments
BarIs 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 Comments
KeyValuePair is not a list, but it could be an entry of a list. Maybe you are looking for a List<>? See stackoverflow.com/questions/23096260/…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<> --> stackoverflow.com/questions/23096260/…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
Comments
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!
6 Comments
Map defined? Is it Angular-specific?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.fromEntriesMap, esp.Map.prototype.entriesandnew Map()constructorSet, esp.Set.prototype.entries
an example of a key value pair is:
[key: string]: string
you can put anything as the value, of course
2 Comments
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?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?Comments
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());
2 Comments
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;
}
3 Comments
Record<string, number> (simply replace "KeyValue" with "Record".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,
}
