bas*_*rat 92
Typescript中是否提供键值对?
是.称为索引签名:
interface Foo {
[key: string]: Bar;
}
let foo:Foo = {};
Run Code Online (Sandbox Code Playgroud)
键string和值是Bar.
您可以使用ES6 Map适当的字典,通过polyfilledcore-js.
Jai*_*ime 51
最简单的方法是:
var indexedArray: {[key: string]: number}
Run Code Online (Sandbox Code Playgroud)
mag*_*ker 25
你也可以考虑使用Record,像这样:
const someArray: Record<string, string>[] = [
{'first': 'one'},
{'second': 'two'}
];
Run Code Online (Sandbox Code Playgroud)
或者这样写:
const someArray: {key: string, value: string}[] = [
{key: 'first', value: 'one'},
{key: 'second', value: 'two'}
];
Run Code Online (Sandbox Code Playgroud)
Jac*_*ler 14
Typescript中是否可以使用键值对?
如果您想到的是C#KeyValuePair <string,string>:不,但是您可以轻松地自己定义一个:
interface KeyValuePair {
key: string;
value: string;
}
Run Code Online (Sandbox Code Playgroud)
用法:
let foo: KeyValuePair = { key: "k", value: "val" };
Run Code Online (Sandbox Code Playgroud)
for*_*d04 12
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
Run Code Online (Sandbox Code Playgroud)
您可以创建一个泛型KeyValuePair类型以实现可重用性:
type KeyValuePair<K extends PropertyKey, V = unknown> = [K, V]
const kv: KeyValuePair<string, string> = ["key", "value"]
Run Code Online (Sandbox Code Playgroud)
type KeyValuePairNamed = [key: string, value: string] // "key" and "value" labels
Run Code Online (Sandbox Code Playgroud)
[key, value]元组还确保与 JS 内置对象的兼容性:
Object,特别是。Object.entries,Object.fromEntriesMap,特别是。Map.prototype.entries和new Map()构造函数Set,特别是。Set.prototype.entriespet*_*r70 10
不是提问者,而是所有其他感兴趣的人:请参阅:如何定义键值对的Typescript Map.其中key是数字,value是对象数组
因此解决方案是:
let yourVar: Map<YourKeyType, YourValueType>;
// now you can use it:
yourVar = new Map<YourKeyType, YourValueType>();
yourVar[YourKeyType] = <YourValueType> yourValue;
Run Code Online (Sandbox Code Playgroud)
干杯!
另一种简单的方法是使用元组:
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10];
// Access elements
console.log("First: " + x["0"] + " Second: " + x["1"]);
Run Code Online (Sandbox Code Playgroud)
输出:
第一:你好第二:10
小智 9
键值对的示例是:
[key: string]: string
您可以输入任何内容作为值-如果您以编程方式填充了类型不同的值,则可以输入:
[key: string]: any
尽管您可以自行决定any:)
小智 5
也可以简单的使用Record
type Foo = Record<string, number>
Run Code Online (Sandbox Code Playgroud)
文档中的进一步用法
| 归档时间: |
|
| 查看次数: |
93242 次 |
| 最近记录: |