我将通用类型定义为
interface IDictionary<TValue> {
[key: string|number]: TValue;
}
但是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;
}
以上都不是。
您可以通过使用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"
如您所见,字符串索引和数字索引可以互换。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句