Interface for dynamic key in typescript

后端 未结 6 1654
一生所求
一生所求 2020-12-05 12:33

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

myObject = {
  \"key\" : [{Object},{Object2},{Object3}],
  \"key         


        
6条回答
  •  不知归路
    2020-12-05 13:09

    { [x: string]: T }
    

    and

    Record
    

    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 = Record
    

    Faster and cleaner than using the Record all the time.

    E.g.:

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

提交回复
热议问题