Lime Brains

Software house where business questions,

How to define type in type-script for dynamic property name?


Problem 😱

You would like to create type for following object with dynamic property name:

const gallery = {
  homepage: {
    key: 'gallery-of-users',
    activeSlide: 1,
  },
  feed: {
    key: 'gallery-of-posts',
    activeSlide: 10
  }
}

Solution 🤓

export interface IGalleryItem {
  key: string;
  activeSlide: string;
}

export interface IGallery {
  [slideKeyWhichIsDynamic:string]: IGalleryItem;
}

Usage:

const gallery: IGallery = {
    ...
}