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


当前回答

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());

其他回答

是键值对可在Typescript?

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

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

用法:

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

最简单的方法是:

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;

如果你想用下面的例子

例如:{ value1:“value1” }

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

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

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

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

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

输出:

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

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

因此,解决方案是:

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

干杯!