1

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' }

1 Answer 1

2
export type RecipeIngredient = {
  name: string;
  quantity: Number;
  measurement: "grams" | "mililitres";
} | {
  name: string;
  quantity: string;
  measurement: "custom";
};
Sign up to request clarification or add additional context in comments.

2 Comments

Easy but problem is when we want to use that variable, we need to manually cast. for e.g. const custom: RecipeIngredient = { ..., measurement: "custom"}; Now when I use it somewhere, just for example, processIt(custom.measurement as 'custom');
Well, union type is more useful for annotating function params. For your case I would just let TS infer the type of custom from value instead of annotate it.

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.