Answer the question
In order to leave comments, you need to log in
How to assign specific keys to an object?
There are a couple of types:
type TFruit = 'apple' | 'banana'
type TFruitProps = 'color' | 'size'
const food = {
apple: {
color: 'red'
}
};
food
= any value of the type TFruit
TFruitProps
Record
type TFood = {
[key in TFruitProps]: string
}
const food:Record<TFruit, TFood> = {
apple: {
color: 'red'
}
}
banana
, although I specified it through the delimiter |
. How to make it optional? Answer the question
In order to leave comments, you need to log in
type TFood = Partial<Record<TFruit, Partial<Record<TFruitProps, string>>>>;
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"
}
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 questionAsk a Question
731 491 924 answers to any question