Home > Mobile >  How to define a type for object with dynamic keys?
How to define a type for object with dynamic keys?

Time:12-06

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

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'

CodePudding user response:

The type should simply be Category[].

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

CodePudding user response:

categories type should be Category[]

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

Demo

  • Related