我有一份菜品清单:
const dishes = [
{
id: 'dish01',
title: 'SALMON CRUNCH',
price: 99,
ingredients: [
'SALMON',
'CRUNCH SALAD',
],
options: [
{
option: 'BASE',
choices: ['RICE', 'SPAGHETTI', 'MIX'],
defaultOption: 'MIX',
},
],
},
{
id: 'dish02',
title: 'GOCHUJANG CHICKEN',
price: 110,
ingredients: [
'GOCHUJANG',
'CHICKEN',
],
options: [
{
option: 'BASE',
choices: ['RICE', 'SPAGHETTI', 'MIX'],
defaultOption: 'MIX',
},
{
option: 'TOPPING',
choices: ['MAYO', 'KETCHUP', 'NONE'],
defaultOption: 'NONE',
},
],
},
...
]然后,我决定使用useReducer (React)来跟踪并构建进入卡片的单个点菜对象。
那么是否可以为每个菜定义一个自定义接口呢?
// types for dish01
type Ingredients = 'SALMON' | 'CRUNCH SALAD'
interface DishOrder {
id: string
withoutIngredients: Ingredients[]
BASE: 'RICE' | 'SPAGHETTI' | 'MIX'
}
// types for dish02
type Ingredients = 'GOCHUJANG' | 'CHICKEN'
interface DishOrder {
id: string
withoutIngredients: Ingredients[]
BASE: 'RICE' | 'SPAGHETTI' | 'MIX'
TOPPINGS: 'MAYO' | 'KETCHUP' | 'NONE'
}如果不是,那么这是不是就像它能得到的类型一样:
interface DishOptions {
[key: string]: string
}
// https://stackoverflow.com/a/45261035/618099
type DishOrder = DishOptions & {
id: string
withoutIngredients: string[]
}发布于 2021-04-20 19:55:05
看起来像是generics的完美案例
type Ingredients = 'SALMON' | 'CRUNCH SALAD'
interface DishOrder<T> {
id: string
withoutIngredients: T[]
BASE: 'RICE' | 'SPAGHETTI' | 'MIX'
TOPPINGS: 'MAYO' | 'KETCHUP' | 'NONE'
}
// const yourDishOrder: DishOrder<Ingredients> = ...发布于 2021-04-20 19:31:32
我会这样做:
enum Ingredient {
Salmon = "Salmon",
CrunchSalad = "Crunch Salad",
...
}
enum Base {
Ris = "Ris",
...
}
enum Topping {
Mayo = "Mayo",
...
}
interface DishOrder {
id: string;
withoutIngredients: Ingredient[];
toppings?: Topping[];
base: Base[];
}这根本不是一个极端的例子。
https://stackoverflow.com/questions/67177994
复制相似问题