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


当前回答

是键值对可在Typescript?

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

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

用法:

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

其他回答

是键值对可在Typescript?

是的。称为索引签名:

interface Foo {
   [key: string]: number;
}


let foo:Foo = {};
foo['hello'] = 123;
foo = {
  'leet': 1337
};
console.log(foo['leet']); // 1337

这里键是字符串,值是数字。

More

你可以使用es6 Map来处理合适的字典,由core-js填充。

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

因此,解决方案是:

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

干杯!

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有Map。你可以用like:

public myMap = new Map<K,V>([
[k1, v1],
[k2, v2]
]);

myMap.get(key); // returns value
myMap.set(key, value); // import a new data
myMap.has(key); // check data

键值对的一个例子是:

[key:字符串]:字符串

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