【问题标题】:How to constraint type?如何约束类型?
【发布时间】:2017-11-17 04:45:51
【问题描述】:

我正在为哈希定义接口:

export interface Hash<ValType> {
    [key: string | number]: ValType;
}

这个错误:

An index signature parameter type must be 'string' or 'number'. (parameter) key: string | number

然后我尝试了:

export interface Hash<KeyType extends number | string, ValType> {
    [key: KeyType]: ValType;
}

同样的错误。

我怎样才能做到这一点?

【问题讨论】:

标签: typescript generics


【解决方案1】:

不能对索引器上的键使用泛型。相反,您需要为每种键类型创建一个接口:

export interface StringHash<T> {
    [key: string]: T;
}

export interface NumberHash<T> {
    [key: number]: T;
}

const x: StringHash<Example> = {};
const y: NumberHash<Example> = {};

希望您可以看到,如果通用密钥有效,它不会为您节省任何工作无法演示的示例:

export interface Hash<TKey, T> {
    [key: TKey]: T;
}

const x: Hash<string, Example> = {};
const y: Hash<number, Example> = {};

如果这是可能的,那么您所要做的就是在每次引用 Hash 时将单词 string 和 number 移动到表达式中出现的位置。 (即它从NumberHash 移动到Hash&lt;number,)。

这已在issue #6641 中讨论过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多