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


当前回答

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

因此,解决方案是:

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

干杯!

其他回答

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

因此,解决方案是:

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

干杯!

键值对的一个例子是:

[key:字符串]:字符串

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

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

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

输出:

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

也可以简单地使用Record

type Foo = Record<string, number>

在文档中进一步使用

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

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