是键,值对可在typescript?如果是,怎么做。任何人都可以提供示例链接。
当前回答
一种简洁的方法是使用元组作为键值对:
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内置对象的兼容性:
物体(尤指物体)。条目,Object.fromEntries Map,尤其是Map.prototype.entries和新的Map()构造函数 Set,尤其是Set.prototype.entries
操场上
其他回答
是键值对可在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?
如果你想到一个c# KeyValuePair<string, string>:不,但你可以很容易地自己定义一个:
interface KeyValuePair {
key: string;
value: string;
}
用法:
let foo: KeyValuePair = { key: "k", value: "val" };
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());
如果你想用下面的例子
例如:{ value1:“value1” }
并根据某些条件动态添加conditionalData,尝试
let dataToWrite: any = {value1: "value1"};
if(conditionalData)
dataToWrite["conditionalData"] = conditionalData
另一种简单的方法是使用元组:
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10];
// Access elements
console.log("First: " + x["0"] + " Second: " + x["1"]);
输出:
第一个:你好,第二个:10
推荐文章
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- Typescript ReferenceError: exports没有定义
- React组件中使用TypeScript的默认属性值
- Angular 5 -复制到剪贴板
- TypeScript枚举对象数组
- Angular 2显示和隐藏一个元素
- 具有构造签名的接口如何工作?
- 'React'指的是一个UMD全局,但当前文件是一个模块
- Angular 2中的“component”不是一个已知的元素
- TypeScript错误:属性“X”在类型“Window”上不存在
- 我怎么能计算在打字稿2日期之间的时间
- 正确使用错误
- 如何修复TS2322:“可以实例化与约束'对象'的不同子类型”?
- 如何在Angular中动态加载外部脚本?
- 当组件属性依赖于当前日期时间时,如何管理Angular2“expression has changed after it was checked”异常