[英]How to define a type for object with dynamic keys?
我正在嘗試使用動態鍵為 object 定義一個類別類型,我認為我成功了,但真的不知道如何在數組中分配它們。
類別.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],
},
//...
];
如何將導入的類別分配到類別屬性中?
編輯:我之前的錯誤:
(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'
類型應該只是Category[]
。
export type SliderProps = {
id: string;
title: string;
description: string;
categories: Category[];
poster: string;
};
類別類型應該是Category[]
export type SliderProps = {
id: string;
title: string;
description?: string;
categories: Category[];
poster?: string;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.