Typescript 中的对象索引键类型 [英] Object index key type in Typescript

查看:57
本文介绍了Typescript 中的对象索引键类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将泛型类型定义为

interface IDictionary<TValue> {
    [key: string|number]: TValue;
}

但是 TSLint 在抱怨.我应该如何定义一个可以作为键的对象索引类型?我也试过这些,但没有运气.

But TSLint's complaining. How am I supposed to define an object index type that can have either as key? I tried these as well but no luck.

interface IDictionary<TKey, TValue> {
    [key: TKey]: TValue;
}

interface IDictionary<TKey extends string|number, TValue> {
    [key: TKey]: TValue;
}

type IndexKey = string | number;

interface IDictionary<TValue> {
    [key: IndexKey]: TValue;
}

interface IDictionary<TKey extends IndexKey, TValue> {
    [key: TKey]: TValue;
}

以上都不起作用.

推荐答案

您可以通过使用IDictionary{ [key: string]: TValue } 因为数值会自动转换为字符串.

You can achieve that just by using a IDictionary<TValue> { [key: string]: TValue } since numeric values will be automatically converted to string.

这是一个用法示例:

interface IDictionary<TValue> {
    [id: string]: TValue;
}

class Test {
    private dictionary: IDictionary<string>;

    constructor() {
       this.dictionary = {}
       this.dictionary[9] = "numeric-index";
       this.dictionary["10"] = "string-index"

       console.log(this.dictionary["9"], this.dictionary[10]);
    }
}
// result => "numeric-index string-index"

如您所见,字符串索引和数字索引可以互换.

As you can see string and numeric indices are interchangeable.

这篇关于Typescript 中的对象索引键类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆