是键值对可在Typescript?

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

471860 次浏览

是键值对可在Typescript?

是的。叫索引签名:

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




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

这里的键是string,值是number

更多的

你可以使用es6 Map作为合适的字典,core-js填充

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

因此,解决方案是:

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;

是键值对可在Typescript?

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

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

用法:

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

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

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

输出:

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

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

键值对的一个例子是:

[key: string]: string

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

你也可以考虑使用Record,像这样:

const someArray: Record<string, string>[] = [
{'first': 'one'},
{'second': 'two'}
];

或者这样写:

const someArray: {key: string, value: string}[] = [
{key: 'first', value: 'one'},
{key: 'second', value: 'two'}
];

一个简洁的方法是使用元组作为键-值对:

const keyVal: [string, string] =  ["key", "value"] // explicit type
const keyVal2 = ["key", "value"] as const // inferred type with const assertion
const [key, val] = ["key", "val"] // usage with array destructuring

你可以为可重用性创建一个泛型KeyValuePair类型:

type KeyValuePair<K extends PropertyKey, V = unknown> = [K, V]
const kv: KeyValuePair<string, string> = ["key", "value"]

TS 4.0

提供了 标记的元组元素提供更好的文档和工具支持:

type KeyValuePairNamed = [key: string, value: string] // "key" and "value" labels

兼容性

[key, value]元组还确保与JS内置对象的兼容性:

游乐场 .

如果你想用下面的例子

< p >例子:{ value1:“value1" } < / p >

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

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


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

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


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

enter image description here

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

也可以简单地使用Record

type Foo = Record<string, number>

文档中进一步使用