Typescript type/object's conditional property feature

Imagine having a recipe ingredient type structured like this

export type RecipeIngredient = {
  name: string;
  amount: Number | string;
  unit: "grams" | "milliliters" | "custom";
};

To illustrate

const apples: RecipeIngredient = { name: 'apples', amount: 200, unit: 'grams' }

This setup works well, but the requirement is to allow the amount to be a string only when the unit is considered custom. Is this achievable?

The ideal scenario

const vanillaExtract: RecipeIngredient = { name: 'vanilla extract', amount: 'a dash', unit: 'custom' }

What should be considered incorrect

const milk: RecipeIngredient = { name: 'milk', amount: '500ml', unit: 'milliliters' }

Answer №1

declare type Ingredient = {
  name: string;
  amount: Number;
  unit: "grams" | "mililitres";
} | {
  name: string;
  amount: string;
  unit: "custom";
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Building basic objects in TypeScript

My current project involves utilizing an interface for vehicles. export interface Vehicle { IdNumber: number; isNew: boolean; contact: { firstName: string; lastName: string; cellPhoneNumber: number; ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...

Seeking assistance with managing Yarn workspaces

My current project involves working on a React Native application for a client. After I had already written a significant amount of code, my client requested a new feature to be added. This feature should have been simple to implement, but due to the compl ...

Issue: The error message "TypeError: React.createContext is not a function" occurs when using Next.js 13 alongside Formik with TypeScript

I'm currently working on creating a form using Formik in NextJs 13 (Typescript). However, the form I designed isn't functioning properly. To troubleshoot, I added code snippets from Formik's examples as shown below. Unfortunately, both my fo ...

What is the best way to implement a dynamic mask using imask in a React

I have a question regarding the implementation of two masks based on the number of digits. While visually they work correctly, when I submit the form, the first mask is always selected. How can I resolve this issue? My solution involves using imask-react ...

Unable to bind to ngModel as it returned as "undefined" in Angular 8

Whenever I bind a property to ngModel, it consistently returns undefined <div> <input type="radio" name="input-alumni" id="input-alumni-2" value="true" [(ngModel) ...

ERROR TypeError: Unable to access the 'nativeElement' property since it is undefined in Angular 5

I have encountered a problem while working on my application. Although similar issues have been asked before, I believe mine is slightly different. In my application, when a user deletes products from their cart, I want to automatically close the modal wi ...

Inquiry regarding modules in Javascript/Typescript: export/import and declarations of functions/objects

I'm fresh to the realm of TypeScript and modules. I have here a file/module that has got me puzzled, and I could really use some guidance on deciphering it: export default function MyAdapter (client: Pool): AdapterType { return { async foo ( ...

Looking for the final entry in a table using AngularJS

Hey everyone, I'm dealing with a table row situation here <tbody> <tr *ngFor="let data of List | paginate : { itemsPerPage: 10, currentPage: p }; let i = index"> <td>{{ d ...

The search for 'Renderer2' in '@angular/core' did not yield any results

After successfully installing Angular Material in my Angular Project by following the instructions provided in the Material documentation, I encountered some issues. Specifically, when attempting to launch the application with 'npm start', I star ...

Troubleshooting: Ngx-Echarts Animation Issue at Startup

I've been working on integrating ngx echarts into my Angular app, but I'm facing an issue with the animation during the initial load of the chart. Take a look at this Stackblitz example where you can see that the bars render quickly on initial lo ...

Connect an Observable to the template with async binding

I've been attempting to link an Observable to a template variable in Angular using the following code: [class.active]="isBookmarked$ | async" During the ngOnInit function, I initialize the Observable: var promise = this.cacheService.getItem(this.bo ...

Employing the keyof operator with the typeof keyword to access an object

What data type should be used for the key variable? I am encountering an error stating that "string" cannot be used to index the type "active1: boolean, active2". const [actives, setActives] = React.useState({ active1: false, active2: false, }); con ...

Issues with Rxjs pipe and Angular's Http.get() functionality are causing complications

Working with an Angular 4 Component that interacts with a Service to fetch data is a common scenario. Once the data is retrieved, it often needs to be transformed and filtered before being utilized. The prevailing method for this task is through the use of ...

Ensuring that environment variables are properly set is essential for effective error handling

I am currently integrating my NodeJS and Typescript App to create new config files that utilize .env variables. If a specific variable is not set, I want to trigger an error. After setting up my config file, I encountered some errors; however, I am unsure ...

Using React and TypeScript to pass member variables

My component Child has a member variable that can change dynamically. While I am aware of passing props and states, is there a more elegant solution than passing member variables through props or other parameters? class Child extends React.Component< ...

Implement Material-UI's built-in validation for form submission

I'm in the process of setting up a form with validation: import React from 'react'; import { useForm } from "react-hook-form"; import axios, {AxiosResponse} from "axios"; import {Box, Button, Container, Grid, Typography} ...

Tips for transitioning from Angular to Angular 2: Overcoming key challenges

Our current Angular project is highly developed, but with the emergence of Angular 2 and its advanced features and improved performance, we are considering migrating our existing work. However, we are concerned about the potential challenges that may ari ...

Potential absence of object.ts(2531)

Currently, I am working on a project using Node.js with Typescript. My task involves finding a specific MongoDB document, updating certain values within it, and then saving the changes made. However, when I try to save the updated document, an error is bei ...

The return type in Typescript for dynamically generated return values

If I have a function in Typescript 2.0 like this: doSomething(): any { const apple: Apple = ... const pears: Pear[] = ... return { apple: apple, pears: pears } } I am aware that the function will always produce an object ...