supvicky
supvicky

Reputation: 55

TypeScript: Getting Value from an Enum Key in Interface

I created an enum named FoodTypes:

enum FoodTypes {
    Meat,
    Veggie,
}

Then I declared an interface named Recipe that contains arrays of objects of FoodTypes.

interface Recipe {
    [FoodTypes.Meat]: [
        { name: 'Beef', val: 120 },
        { name: 'Pork', val: 200 },
    ],
    [FoodTypes.Veggie]: [
        { name: 'Mushroom', val: 30 },
        { name: 'Lettuce', val: 10 },
    ],
};

How do I access a specific value in the interface? For example, I'd like to get the val of Beef. // should be 120

Thanks so much!

Edit: @captain-yossarian For example, if I want to pass in the value later in a function as it changes dynamically (using React Redux in front-end), would I be able to do so? I know that the following wouldn't work since I'm referring to a type:

function getBeefVal(recipe: Recipe) {
return "Beef Val: " + Recipe[FoodTypes.Meat][0]['val'];
}

Upvotes: 1

Views: 277

Answers (1)

type Beef = Recipe[FoodTypes.Meat][0]['val'] // 120

You can use the square bracket notation to get a nested property of an interface. Just like plain JS.

if I want to pass in the value later in a function as it changes dynamically (using React Redux in front-end), would I be able to do so? I know that the following wouldn't work since I'm referring to a type:

TS has two scopes. One for types, let's name it TypeScope - another one for values - ValueScope

It is impossible to use types from TypeScope in the ValueScope. Because all types are removed after the compilation.

In some cases it is possible to use values from ValueScope in TypeScope. For example classes.

class A {
    age: number = 0
}

const x: A = { age: 42 } // ok

In above example I have used A class from ValueScope as a type in TypeScope.

Upvotes: 2

Related Questions