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


当前回答

KeyValue接口存在于使用typescript的angular库中。 如果你的项目是角型的,你就有了这个通用接口。 如果你在angular中不使用TS,你也可以使用它的声明来获得一个漂亮的通用KeyValue接口。

export declare interface KeyValue<K, V> {
    key: K;
    value: V;
}

其他回答

是键值对可在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;

干杯!

最简单的方法是:

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:字符串]:字符串

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

KeyValue接口存在于使用typescript的angular库中。 如果你的项目是角型的,你就有了这个通用接口。 如果你在angular中不使用TS,你也可以使用它的声明来获得一个漂亮的通用KeyValue接口。

export declare interface KeyValue<K, V> {
    key: K;
    value: V;
}