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


当前回答

另一种简单的方法是使用元组:

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10];
// Access elements
console.log("First: " + x["0"] + " Second: " + x["1"]);

输出:

第一个:你好,第二个:10

其他回答

最简单的方法是:

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;

是键值对可在Typescript?

如果你想到一个c# KeyValuePair<string, string>:不,但你可以很容易地自己定义一个:

interface KeyValuePair {
    key: string;
    value: string;
}

用法:

let foo: KeyValuePair = { key: "k", value: "val" };

如果你想用下面的例子

例如:{ value1:“value1” }

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

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

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

不是对提问者,而是对所有感兴趣的人: 参见:如何定义键值对的Typescript映射。其中键是一个数字,值是一个对象数组

因此,解决方案是:

let yourVar: Map<YourKeyType, YourValueType>;
// now you can use it:
yourVar = new Map<YourKeyType, YourValueType>();
yourVar[YourKeyType] = <YourValueType> yourValue;

干杯!

你也可以考虑使用Record,像这样:

const someArray: Record<string, string>[] = [
    {'first': 'one'},
    {'second': 'two'}
];

或者这样写:

const someArray: {key: string, value: string}[] = [
    {key: 'first', value: 'one'},
    {key: 'second', value: 'two'}
];