A concise way is to use a tuple as key-value pair:
const keyVal: [string, string] = ["key", "value"] // explicit type
// or
const keyVal2 = ["key", "value"] as const // inferred type with const assertion
[key, value]
tuples also ensure compatibility to JS built-in objects:
Object
, esp. Object.entries
, Object.fromEntries
Map
, esp. Map.prototype.entries
and new Map()
constructorSet
, esp. Set.prototype.entries
You can create a generic KeyValuePair
type for reusability:
type KeyValuePair<K extends string | number, V = unknown> = [K, V]
const kv: KeyValuePair<string, string> = ["key", "value"]
Upcoming TS 4.0 provides named/labeled tuples for better documentation and tooling support:
type KeyValuePairNamed = [key: string, value: string] // add `key` and `value` labels
const [key, val]: KeyValuePairNamed = ["key", "val"] // array destructuring for convenience