是键,值对可在typescript?如果是,怎么做。任何人都可以提供示例链接。


当前回答

一种简洁的方法是使用元组作为键值对:

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

你可以创建一个通用的KeyValuePair类型来实现重用:

type KeyValuePair<K extends PropertyKey, V = unknown> = [K, V]
const kv: KeyValuePair<string, string> = ["key", "value"]

TS 4.0

为更好的文档和工具支持提供标记的元组元素:

type KeyValuePairNamed = [key: string, value: string] // "key" and "value" labels

兼容性

[key, value]元组还可以确保与JS内置对象的兼容性:

物体(尤指物体)。条目,Object.fromEntries Map,尤其是Map.prototype.entries和新的Map()构造函数 Set,尤其是Set.prototype.entries

操场上

其他回答

最简单的方法是:

var indexedArray: {[key: string]: number}

用法:

var indexedArray: {[key: string]: number} = {
    foo: 2118,
    bar: 2118
}

indexedArray['foo'] = 2118;
indexedArray.foo= 2118;

let foo = indexedArray['myKey'];
let bar = indexedArray.myKey;

键值对的一个例子是:

[key:字符串]:字符串

当然,你可以把任何东西作为值

如果你想用下面的例子

例如:{ value1:“value1” }

并根据某些条件动态添加conditionalData,尝试

let dataToWrite: any = {value1: "value1"};

if(conditionalData)
   dataToWrite["conditionalData"] = conditionalData

也可以简单地使用Record

type Foo = Record<string, number>

在文档中进一步使用

一种简洁的方法是使用元组作为键值对:

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

你可以创建一个通用的KeyValuePair类型来实现重用:

type KeyValuePair<K extends PropertyKey, V = unknown> = [K, V]
const kv: KeyValuePair<string, string> = ["key", "value"]

TS 4.0

为更好的文档和工具支持提供标记的元组元素:

type KeyValuePairNamed = [key: string, value: string] // "key" and "value" labels

兼容性

[key, value]元组还可以确保与JS内置对象的兼容性:

物体(尤指物体)。条目,Object.fromEntries Map,尤其是Map.prototype.entries和新的Map()构造函数 Set,尤其是Set.prototype.entries

操场上