Interface for dynamic key in typescript

时间:2016-08-31 18:33:53

标签: typescript

I have an Object like this that is created by underscore's _.groupBy() method.

myObject = {
  "key" : [{Object},{Object2},{Object3}],
  "key2" : [{Object4},{Object5},{Object6}],
  ...
}

How would I define that as an Interface with TypeScript? i don't want to simply define it as myObject:Object = { ... but rather have an own type for it.

6 个答案:

答案 0 :(得分:71)

您的对象看起来像Object数组的字典

interface Dic {
    [key: string]: Object[]
}

答案 1 :(得分:16)

TypeScript中现在有一个专用的Record类型:

const myObject: Record<string, object[]> = { ... }

另外,请考虑尽可能键入密钥:

type MyKey = 'key1' | 'key2' | ...

const myObject: Record<MyKey, object[]> = { ... }

答案 2 :(得分:2)

不了解接口,对于动态对象,我们可以执行以下操作:

let memoTable: { [k: number]: number } = {};
memoTable[1]=5;
memoTable[2]=7;

答案 3 :(得分:2)

不是使用Object作为类型,而是使用Record

interface myObjInterface {
  [key: string]: Record<string, any>[]
}

答案 4 :(得分:2)

{ [x: string]: T }

Record<string, T>

通常可以满足您的所有目标。但是,我到达一个奇怪的地步,在执行某些类型操作之后,第一个选项同时返回了[x:字符串]和[x:数字],而我无法使用Record,因为它是递归的类型操作,而Typescript抛出错误,表明我的递归类型不是通用的。

因此,通过研究很小的Record代码,我得出了解决我复杂问题的解决方案:

{ [P in string]: T }

编辑:通常我在utils.ts文件中编写的每个Typescript代码中都包含此代码:

export type obj<T = unknown> = Record<string, T>

比一直使用记录更快捷,更干净。

例如:

type MyObjectType = {
  propA: obj; // An object with unknown props
  propB: obj<number>; // An object with number props
}

答案 5 :(得分:0)

我建议使用Map解决方案,也许对某人有用:

type TKey = 'key1' | 'key2' | 'key3';
type TValue = object[];

type TMapper = Map<TKey, TValue>; // But also you can use Record instead of Map