Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to define a type for object with dynamic keys?

I’m trying to define a category type for object with dynamic keys and I think I succeeded in that but don’t really know how to assign them in Array.

category.ts

interface CategoryType {
  name: string;
  color: string;
}

interface Category extends CategoryType {
  [x: string]: {};
}

export const Categories: Record<string, Category> = {
  action: { name: "Action", color: "#f44336" },
  animation: { name: "Animation", color: "#dcf836" },
  adventure: { name: "Adventure", color: "#233a50" },
  //...
};

slider.tsx

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { Categories } from "@lib/types/category";

export type SliderProps = {
  id: string;
  title: string;
  description: string;
  categories: typeof Categories;
  poster: string;
};

const slides: Readonly<SliderProps[]> = [
  {
    id: "1149",
    title: "Blade Runner 2049",
  // I want to be able to add multiple categories for each movie
    categories: [Categories.Action, Categories.Animation],
  },
  //...
];

How can I assign the imported Categories into the categories property?

Edit:
The error I had before:

(property) categories: Record<string, Category>
Type 'Category[]' is not assignable to type 'Record<string, Category>'.
  Index signature for type 'string' is missing in type 'Category[]'.ts(2322)
slider.tsx(13, 3): The expected type comes from property 'categories' which is declared here on type 'SliderProps'

>Solution :

categories type should be Category[]

export type SliderProps = {
  id: string;
  title: string;
  description?: string;
  categories: Category[];
  poster?: string;
};

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading