What is the process of creating a TypeScript interface that accommodates various schemas?

Trying to establish a Consume type with two different payloads.

interface Eat {
  category: 'meat' | 'vegetable'
}
interface Drink {
  size: string
}
interface Consume {
   type: 'eat' | 'drink'
   payload: Eat | Drink
}

Encountering issues with if statements

function doSomething(c: Consume): string {
   if (c.type === 'Eat') {
      const e: Eat = c.payload            <----- ERRORS
      return e.category
   }
   return ''
}

Errors triggered:

Type Eat | Drink is not assignable to type 'Drink'. Property 'size' is missing in type 'Eat' but required in type 'Drink'. ts(2322)

Questioning the feasibility of having two distinct schemas within a TypeScript interface Consume.

Answer №1

Here is a way to accomplish this task.

interface Cook {
  option: 'grill' | 'steam'
}
interface Brew {
  method: string
}
interface Prepare {
   choice: 'cook' | 'brew'
   details: Cook | Brew
}

function doTask(p: Prepare): string {
   if (p.choice === 'cook') {
      const m: Cook = p.details as Cook;
      return m.option;
   }
   return ''
}

Answer №2

After some rearranging, I was able to update the schema in TypeScript without needing X as typeY thanks to the format shown below.

type Action = Eat | Drink

interface Eat {
  type: 'eat'
  payload: EatPayload
}
interface EatPayload {
   category: 'meat' | 'vegetable'
}

interface Drink {
  type: 'drink'
  payload: DrinkPayload
}
interface DrinkPayload {
  size: string
}

function doSomething(action: Action): string {
   if (action.type === 'eat') {
      return action.payload.category;
   }
   return ''
}

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

Argument typed with rest properties in Typescript objects

I'm relatively new to Typescript and have managed to add typings to about 90% of my codebase. However, I'm struggling with rest/spread operators. While going through our code today (which I didn't write), I came across this snippet that does ...

Performing an Axios POST request in a React Native and React app using JSON.stringify and Blob functionality

I am currently developing an application where I have encountered an issue when calling an API endpoint in react native. Interestingly, the web app (built with React) does not encounter any errors. Here is the code for the web app using React with TypeScri ...

Learn how to prevent the rendering of a specific section of code using JavaScript/TypeScript, similar to the functionality of *ngIf in Angular

When it comes to hiding specific parts of HTML code, using comments or CSS with display:none is one option, but these are still accessible in the developer tools. How can we leverage the features of JavaScript or TypeScript to prevent these sections from ...

Developers can leverage Node4 and Gulp to seamlessly integrate TypeScript with EcmaScript2015 in their

When converting TypeScript to ES2015, I encounter the need for async/await functionality. However, I must then convert the ES2015 code to be compatible with Node4, which does not fully support ES2015 features. The issue arises when using TypeScript defini ...

Having trouble with the lodash find function in my Angular application

npm install lodash npm install @types/lodash ng serve import { find, upperCase } from 'lodash'; console.log(upperCase('test')); // 'TEST' console.log(find(items, ['id', id])) // TypeError: "Object(...)(...) is un ...

Issue with retrieving the positions of two numbers in an array

I encountered a challenge: I have an array of integers nums and an integer target. My goal is to find the indices of two numbers in the array that add up to the specified target. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Thi ...

Is there a way to attach a Blob/File array to formData in typescript?

If I didn't have an ARRAY of files, this method would work perfectly. However, it needs to be in the form of an Array. let file1 = new File([""], "filename"); let file2 = new File([""], "filename"); let fi ...

Issue encountered with combineLatest following upgrade of rxjs from version 6.x to 7.x

Upon upgrading rxjs from version 6.6.6 to 7.4.0, an error surfaced in my combineLatest function. searchQuery = new FormControl(null); searchStatus = new FormControl<UserStatus>('ALL'); searchParams$ = combineLatest( this.searchQuery.valu ...

When implementing a custom uploadHandler, the PrimeNG File Upload Progress may not accurately reflect the upload progress

Exploring the capabilities of the PrimeNG File Upload Component I have customized the upload process to connect with an API using a special uploadHandler as shown below: <p-fileUpload #fileUpload name="fileUpload" (uploadHandle ...

Encountering a ReactJS and TypeScript issue with error code TS2322: Unable to assign type to 'IntrinsicAttributes & IntrinsicClassAttributes'

I encountered a TS2322 error when trying to pass the searchForBooks method as props from the JumboBooks component to the SearchBooks component: JumboBooks.tsx (Parent) import { RouteComponentProps } from 'react-router'; ... export class JumboBo ...

I'm curious, can you simplify this code snippet by incorporating a lambda function?

Can you help me simplify this lambda expression? I'm only able to use a map function for now. Thanks in advance! array.map(val => { if (val.num !== 1) { val.num -= 1; } }); ...

Delete information based on its unique identifier

Currently, I am trying to remove data from a list but encountering a small issue with the following code. Component Code removeSelectedRows(){ console.log(this.selection.selected.map(item => item.userId)) const selectedRowIds = this.selection. ...

Angular function triggered by clicking that takes two parameters

Is there a way to pass two arguments in this method? <tr *ngFor="let match of item.matches " (click)="openMatchContent(match,$event)" openMatchContent(match: any,event:any) {} When I try to run this code, I receive an error statin ...

What is the process for calling subjects dynamically in a service?

Do you have a service with the following subjects? subjectOne$ = new Subject<Partial<boolean>>(); subjectTwo$ = new Subject<Partial<boolean>>(); subjectThree$ = new Subject<Partial<boolean>>(); subjectFour$ = new ...

Ionic 4 - Best practices for handling asynchronous data with multiple observables

I successfully accessed this route: http://localhost:8100/questions/question?id=3 However, I am facing a challenge in handling two subscribers simultaneously. The first subscriber is responsible for loading the questions array from an external service. ...

Troubleshooting compilation issues when using RxJS with TypeScript

Having trouble resolving tsc errors in the code snippet below. This code is using rxjs 5.0.3 with tsc 2.1.5 import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import 'rxjs/Rx'; let subject ...

Is there a way to alter the value of an Observable using Knockout and Typescript within its subscription?

Question: What is the best way to update the value of an Observable from within its subscription using Knockout and Typescript? I am currently in the process of refactoring some old Knockout code to use Typescript. While going through the code, I came acr ...

What is the best way to export an overloaded function in TypeScript?

Trying to figure out how to overload a function in TypeScript so it can determine the type of arg2 based on the value of arg1. Arg1 has a list of known values. Here's a rough example of what I'm attempting: interface CatArgs {legs : number} int ...

Display or conceal password text with Nativescript

I am working on a login form where I need to toggle the visibility of the password text. Below is the code snippet that I have implemented. Here is the code I tried: <GridLayout margin="10" verticalAlignment="center" backgroundColor="#ffffff"> ...

When incorporating @pokusew/pcsclite into an Angular2/Electron project, a TypeError is triggered

In my Electron project with Angular CLI, I am attempting to implement NFC functionality by incorporating the @pokusew/pcsclite library in one of my components. I am using import * as pcsclite from "../../node_modules/@pokusew/pcsclite" to import ...