[英]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.我正在尝试使用动态键为 object 定义一个类别类型,我认为我成功了,但真的不知道如何在数组中分配它们。
category.ts类别.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 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'
The type should simply be Category[]
.类型应该只是
Category[]
。
export type SliderProps = {
id: string;
title: string;
description: string;
categories: Category[];
poster: string;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.