Reputation: 1565
Let's say I have a recipe ingredient type that looks like this
export type RecipeIngredient = {
name: string;
quantity: Number | string;
measurement: "grams" | "mililitres" | "custom";
};
Example
const potatoes: RecipeIngredient = { name: 'potatoes', quantity: 100, measurement: 'grams' }
which is fine, but I also want to have the quantity as a string only when the measurement is custom. Is this possible?
Correct example
const rosemary: RecipeIngredient = { name: 'rosemary', quantity: 'a handful', measurement: 'custom' }
What I want to be invalid
const fish: RecipeIngredient = { name: 'fish', quantity: '100g', measurement: 'grams' }
Upvotes: 1
Views: 35
Reputation: 19947
export type RecipeIngredient = {
name: string;
quantity: Number;
measurement: "grams" | "mililitres";
} | {
name: string;
quantity: string;
measurement: "custom";
};
Upvotes: 2