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


当前回答

也可以简单地使用Record

type Foo = Record<string, number>

在文档中进一步使用

其他回答

也可以简单地使用Record

type Foo = Record<string, number>

在文档中进一步使用

是键值对可在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填充。

如果你想用下面的例子

例如:{ 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;

干杯!

是键值对可在Typescript?

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

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

用法:

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