字符串或数字字典类型参数

Lod*_*rds 5 typescript

我有这个功能:

interface NumDict<T> {
  [key : number] : T
}

export function mapNumDictValues<T,R>(dict: NumDict<T>, f: (v: T, key?: number) => R): NumDict<R> {
  let emptyDict : NumDict<R> = {};
  return Object.keys(dict).reduce((acc, key) => {
    const keyInt = parseInt(key);
    acc[keyInt] = f(dict[keyInt], keyInt);
    return acc;
  }, emptyDict);
}
Run Code Online (Sandbox Code Playgroud)

现在我希望它适用于字符串索引字典以及数字索引字典,例如:

function mapDictValues<K extends string|number,T,R>(obj: {[id: K]: T}, f: (v: T, key?: K) => R): {[id: K]: R} {
Run Code Online (Sandbox Code Playgroud)

但是,这让我出现了这个错误:

error TS1023: An index signature parameter type must be 'string' or 'number'.
Run Code Online (Sandbox Code Playgroud)

有办法吗?

小智 2

尝试这个:

interface IStringToNumberDictionary {
    [index: string]: number;
}


interface INumberToStringDictionary {
    [index: number]: string;
}

type IDictionary = IStringToNumberDictionary | INumberToStringDictionary;
Run Code Online (Sandbox Code Playgroud)

例子:

let dict: IDictionary = Object.assign({ 0: 'first' }, { 'first': 0 });
let numberValue = dict["first"]; // 0
let stringValue = dict[0]; // first
Run Code Online (Sandbox Code Playgroud)

在你的情况下是这样的:

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


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

type IDictionary<T> = IStringKeyDictionary<T> | INumberKeyDictionary<T>;
Run Code Online (Sandbox Code Playgroud)