D
D
dmitry-toster2021-01-30 02:22:55
typescript
dmitry-toster, 2021-01-30 02:22:55

How to assign specific keys to an object?

There are a couple of types:

type TFruit = 'apple' | 'banana'
type TFruitProps = 'color' | 'size'

How to make such a structure valid?
const food = {
    apple: {
        color: 'red'
    }
};

i.e. property of the object food= any value of the type TFruit
value of this property = object with the key of the type TFruitProps
I am trying to do this throughRecord
type TFood = {
    [key in TFruitProps]: string
}

const food:Record<TFruit, TFood> = {
    apple: {
        color: 'red'
    }
}

However, TS swears at the missing key banana, although I specified it through the delimiter |. How to make it optional?
playground

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2021-01-30
@dmitry-toster

type TFood = Partial<Record<TFruit, Partial<Record<TFruitProps, string>>>>;

K
Konstantin, 2021-01-30
@Junart1

This will work, but not very nicely:

type TFruit = 'apple' | 'banana'
type TFruitProps = 'color' | 'size';
type KEYS = {
    'prop1': null, 'prop2':null , 'prop3': null;
}


type ThreeStringProps = Record<keyof KEYS, TFruitProps>;

let a:ThreeStringProps = {
    prop1: "color",
    prop2: "color",
    prop3: "color"
}

Better solution:
type TFruit = 'apple' | 'banana'
type TFruitProps = 'color' | 'size';
type Keys = "prop1" | "prop2" | "prop3";

type ThreeStringProps = Partial<Record<Keys, TFruitProps>>;

let a:ThreeStringProps = {
    prop1: "color",
    prop2: "color",
    prop3: "color"
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question