Typescript中的对象索引键类型

Rob*_*nik 25 typescript typescript-generics

我将我的泛型类型定义为

interface IDictionary<TValue> {
    [key: string|number]: TValue;
}
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

以上都不是.

那怎么样呢?

小智 28

你可以通过使用一个IDictionary<TValue> { [key: string]: TValue }自动转换为字符串来实现这一点 .

以下是一个用法示例:

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"
Run Code Online (Sandbox Code Playgroud)

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


Nit*_*mer 19

在javascript中,对象的键只能是字符串(在es6符号中也是如此).
如果你传递一个数字,它会转换成一个字符串:

let o = {};
o[3] = "three";
console.log(Object.keys(o)); // ["3"]
Run Code Online (Sandbox Code Playgroud)

如你所见,你总能得到{ [key: string]: TValue; }.

使用Typescript,您可以使用numbers键作为键来定义地图:

type Dict = { [key: number]: string };
Run Code Online (Sandbox Code Playgroud)

并且编译器将检查在分配值时始终将数字作为键传递,但在运行时,对象中的键将是字符串.

因此,您可以拥有{ [key: number]: string }{ [key: string]: string }不拥有string | number以下内容的联合:

let d = {} as IDictionary<string>;
d[3] = "1st three";
d["3"] = "2nd three";
Run Code Online (Sandbox Code Playgroud)

您可能希望d在这里有两个不同的条目,但实际上只有一个.

你可以做的是使用Map:

let m = new Map<number|string, string>();
m.set(3, "1st three");
m.set("3", "2nd three");
Run Code Online (Sandbox Code Playgroud)

在这里,您将有两个不同的条目.