是键,值对可在typescript?如果是,怎么做。任何人都可以提供示例链接。
当前回答
是键值对可在Typescript?
如果你想到一个c# KeyValuePair<string, string>:不,但你可以很容易地自己定义一个:
interface KeyValuePair {
key: string;
value: string;
}
用法:
let foo: KeyValuePair = { key: "k", value: "val" };
其他回答
如果你想用下面的例子
例如:{ value1:“value1” }
并根据某些条件动态添加conditionalData,尝试
let dataToWrite: any = {value1: "value1"};
if(conditionalData)
dataToWrite["conditionalData"] = conditionalData
是键值对可在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填充。
KeyValue接口存在于使用typescript的angular库中。 如果你的项目是角型的,你就有了这个通用接口。 如果你在angular中不使用TS,你也可以使用它的声明来获得一个漂亮的通用KeyValue接口。
export declare interface KeyValue<K, V> {
key: K;
value: V;
}
不是对提问者,而是对所有感兴趣的人: 参见:如何定义键值对的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;
推荐文章
- 从元组/数组值派生联合类型
- 如何在Angular2 ngSwitch语句中使用typescript enum值
- 找到合成属性@panelState。请在您的应用程序中包含“BrowserAnimationsModule”或“NoopAnimationsModule”。
- Angular 2+和debounce
- 在TypeScript箭头函数中指定返回类型
- 如何使用jQuery与TypeScript
- Angular 2模板中的标签是什么意思?
- Typescript接口-可能使“一个或另一个”属性要求?
- 如何扩展/继承组件?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- Typescript ReferenceError: exports没有定义
- React组件中使用TypeScript的默认属性值
- Angular 5 -复制到剪贴板
- TypeScript枚举对象数组
- Angular 2显示和隐藏一个元素