1

I'm trying to see if I can get VS Code to assist me when typing an object with predefined types.

A dish object can look like this:

{
      "id": "dish01",
      "title": "SALMON CRUNCH",
      "price": 120,
      "ingredients": [
        "MARINERAD LAX",
        "PICKLADE GRÖNSAKER",
        "KRISPIG VITLÖK",
        "JORDÄRTSKOCKSCHIPS",
        "CHILIMAJONNÄS"
      ],
      "options": [
        {
          "option": "BAS",
          "choices": ["RIS", "GRÖNKÅL", "MIX"],
          "defaultOption": "MIX"
        }
      ]
}

My current attempt looks like this

enum DishOptionBaseChoices {
  Rice = 'RIS',
  Kale = 'GRÖNKÅL',
  Mix = 'MIX',
}

type DishOption<T> = {
  option: string
  choices: T[]
  defaultOption: T
}

type DishOptions = {
  options: DishOption<DishOptionBaseChoices>[]
}

type Dish = {
  id: string
  title: string
  price: number
  ingredients: string[]
  options: DishOptions
}

(not sure if some of them should be interface instead of type)

the plan is to make enums for all "types" of options. The auto-suggestion works fine with the id but not when writing the options.

vscode example

Working solution

type ChoiceForBase = 'RIS' | 'GRÖNKÅL' | 'MIX'

type DishOption<OptionType, ChoiceType> = {
  option: OptionType
  choices: ChoiceType[]
  defaultOption: ChoiceType
}

type Dish = {
  id: string
  title: string
  price: number
  ingredients: string[]
  options: DishOption<'BAS', ChoiceForBase>[]
}
0

1 Answer 1

2

On type Dish you defined options: DishOptions, but then on type DishOptions you again defined a property options. So with you current types definition your options property looks like this:

const dish: Dish = {
    options: {
        options: [{
            choices: ...
        }]
    }
}

If you want options to be an array of DishOption change your Dish definition:

type Dish = {
    id: string
    title: string
    price: number
    ingredients: string[]
    options: DishOption<DishOptionBaseChoices>[]
}
Sign up to request clarification or add additional context in comments.

3 Comments

Good catch! It now suggest the keys. Shouldn't it also suggest the string for defaultOption when typing?
Arhh.. I just have to use a type with | instead of enum
DishOptionBaseChoices is enum, that's not the same as string. It will suggest you the enum values if you try typing this: defaultOption: DishOptionBaseChoices. If you really want defaultOption to be just a string you can define your type like this: type DishOptionBaseChoices = 'RIS' | 'GRÖNKÅL' | 'MIX'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.