john_per
john_per

Reputation: 320

TS interface for dynamic key in object

I would like to write the proper interface for this object. The key of step should be dynamic and the value is boolean. This is the object:

const obj = {
  A: {
    step: {
      a: true,
      b: true,
      c: true,
    },
  },
  B: {
    step: {
      a: true,
      d: true,
    },
  },
  C: {
    step: {
      e: true,
      f: true,
      g: true,
    },
  },
}

So far I have tried this, but I still got an error.

interface OBJ_INTERFACE {
  side: {
    step: {
      [key: string]: boolean,
    }
  }
}

Upvotes: 0

Views: 234

Answers (2)

Aleksey L.
Aleksey L.

Reputation: 38046

You can extract Step type and reuse it in interface:

type Side = {
  step: {
    [key: string]: boolean,
  }
};

interface OBJ_INTERFACE {
  A: Side;
  B: Side;
  C: Side;
}

Playground


Or define a mapped type:

type OBJ_INTERFACE = {
  [P in 'A' | 'B' | 'C']: {
    step: {
      [key: string]: boolean,
    }
  }
}

Playground

Upvotes: 1

Richard Dunn
Richard Dunn

Reputation: 6780

You don't detail the error, so I can only assume it stems from trying to use the interface as such:

const obj: OBJ_INTERFACE = {
  A: {
    step: {
      ...
    }
  }
}

In which case, your interface doesn't account for the side property being dynamically named as 'A' | 'B' | 'C'.

Try making side dynamic as well:

interface OBJ_INTERFACE {
    [key: string]: {
      step: {
        [key: string]: boolean
    }
  }
}

Upvotes: 1

Related Questions