如何在 TypeScript 中创建通用 Map 接口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34686200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:12:03  来源:igfitidea点击:

How to create generic Map interface in TypeScript

typescript

提问by Chic

I would like to create a Map interface in TypeScript but I cannot seem to figure out how to constrain the property accessor to please the compiler

我想在 TypeScript 中创建一个 Map 接口,但我似乎无法弄清楚如何约束属性访问器来取悦编译器

Desired Interface

所需接口

export interface IMap<I extends string | number, T> {
  [property: I]: T;
}

Error:

错误:

An index signature type must be 'string' or 'number'

索引签名类型必须是“字符串”或“数字”

回答by Seamus

You are allowed to define both a string and numeric index signature.

您可以定义字符串和数字索引签名。

From the spec:

规范

An object type can contain at most one string index signature and one numeric index signature.

一个对象类型最多可以包含一个字符串索引签名和一个数字索引签名。

So you can do this:

所以你可以这样做:

interface IMap<T> {
    [index: string]: T;
    [index: number]: T;
} 

Is that what you were after?

那是你追求的吗?

Also, when you define only a string index signature:

此外,当您仅定义字符串索引签名时:

Specifically, in a type with a string index signature of type T, all properties and numericindex signatures must have types that are assignable to T.

具体来说,在具有类型 T 的字符串索引签名的类型中,所有属性和数字索引签名都必须具有可分配给 T 的类型。

And so:

所以:

class Foo {
    [index: string]: number;
}

let f = new Foo();

f[1] = 1; //OK

f[6] = "hi"; //ERROR: Type 'string' is not assignable to type 'number'