首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用动态关键点在对象上动态设置类型

如何使用动态关键点在对象上动态设置类型
EN

Stack Overflow用户
提问于 2021-04-20 19:26:02
回答 2查看 45关注 0票数 0

我有一份菜品清单:

代码语言:javascript
复制
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)来跟踪并构建进入卡片的单个点菜对象。

那么是否可以为每个菜定义一个自定义接口呢?

代码语言:javascript
复制
// 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'
}

如果不是,那么这是不是就像它能得到的类型一样:

代码语言:javascript
复制
interface DishOptions {
  [key: string]: string
}

// https://stackoverflow.com/a/45261035/618099
type DishOrder = DishOptions & {
  id: string
  withoutIngredients: string[]
}
EN

回答 2

Stack Overflow用户

发布于 2021-04-20 19:55:05

看起来像是generics的完美案例

代码语言:javascript
复制
type Ingredients = 'SALMON' | 'CRUNCH SALAD'

interface DishOrder<T> {
  id: string
  withoutIngredients: T[]
  BASE: 'RICE' | 'SPAGHETTI' | 'MIX'
  TOPPINGS: 'MAYO' | 'KETCHUP' | 'NONE'
}

// const yourDishOrder: DishOrder<Ingredients> = ...
票数 2
EN

Stack Overflow用户

发布于 2021-04-20 19:31:32

我会这样做:

代码语言:javascript
复制
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[];
}

这根本不是一个极端的例子。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67177994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档