Interface for dynamic key in typescript

Your object looks like a dictionary of Object arrays

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

There's now a dedicated Record type in TypeScript:

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

Also, consider typing the keys whenever possible:

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

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

{ [x: string]: T }

and

Record<string, T>

usually will serve for all your objectives. However, I got to a strange point where after some type operations the first option was returning to me both [x: string] and [x: number], and I wasn't being able to use the Record, as it was a recursive type operation and Typescript was throwing an error saying my recursive type wasn't generic.

So, studying the really small Record code, I came to this solution that solved my complex problem:

{ [P in string]: T }

Edit: I also usually have this in every Typescript code I write, in a utils.ts file:

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

Faster and cleaner than using the Record all the time.

E.g.:

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

Tags:

Typescript