Different combinations of fields in Typescript types

Take a look at this defined type:

type MyType =
  | { a: number }
  | { b: number }
  | { c: number }
  | ({ b: number } & { c: number });

The goal is to prevent the combination of 'a' with either 'b' or 'c'.

  const o1: MyType = { a: 10 };             // only 'a': OK
  const o2: MyType = { b: 10 };             // only 'b': OK
  const o3: MyType = { c: 10 };             // only 'c': OK
  const o4: MyType = { b: 10, c: 10 };     // combine 'b' and 'c': OK

  // const o5: MyType = {};                     // Forbidded (no fields)
  const o6: MyType = { a: 10, b: 10 };        // Forbidden ('a' and 'b' should not be combinable)

I'm confused because TypeScript allows me to create object 'o6'. Ideally, combining 'a' and 'b' should not be allowed...

Any thoughts or suggestions?

Thank you

Answer №1

Although it may not be visually appealing, utilizing XOR can assist you in this particular scenario.

type MyType =
  | { a: number, b?: never }
  | { b: number, a?: never }
  | { c: number }
  | ({ b: number } & { c: number });

To simplify comprehension, it is helpful to think of Union as a combination of any type, rather than just an OR operation.

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

Incorporating a module from a nearby component repository into the primary task

As I work on developing a component library using React, TypeScript, Rollup, and Styled Components, I have made significant progress but have hit a roadblock that seems to be the final hurdle. The button component in my library is successfully exported, a ...

Exploring Ngu-Carousel in Angular 7: Importing JSON data for a dynamic display

After attempting to import data from JSON and display it using ngu-carousel, I encountered an error. The error shows "length of undefined" Subsequently, when I try to click on the previous/next button, another error appears. This error states "innerHTML ...

Encountered an issue in GoJS with Angular 4: ERROR TypeError: Unable to access property 'class' of null at Function.F.fromJson.F.fromJSON

I have just started exploring GoJS and decided to create a sample project by utilizing the Kanban sample available on the GoJs website. I attempted to use Angular and Typescript for this, but encountered an error. AppComponent.html:1 ERROR TypeError: Cann ...

What allows us to create an instance of a generic class even without defining the generic type parameter?

It is intriguing how TypeScript allows the instantiation of a generic class without specifying the actual generic type parameter. For instance, in the code snippet below, the class Foo includes a generic type parameter T. However, when creating a new Foo i ...

Tips on integrating ActiveX controls in Angular

I built my project using Angular 6 and TypeScript in Visual Studio Code. The browser being used is IE11. Unfortunately, when I try to run the code written in app.component.html, it doesn't work as expected. The HTML code causing the issue is: <d ...

Is it possible to measure the CPU utilization in a TypeScript application programmatically?

Is there a method to calculate CPU usage as a percentage and record it in a file every 20 milliseconds? I'm interested in exploring different approaches for accomplishing this task. Your insights would be greatly appreciated! I've come across so ...

Maintain the spacing of an element when utilizing *ngFor

Using Angular.js and *ngFor to loop over an array and display the values. The goal is to preserve the spaces of elements in the array: string arr1 = [" Welcome Angular ", "Line1", "Line2", " Done "] The ...

Error in Typescript: The type 'Element' does not have a property named 'contains'

Hey there, I'm currently listening for a focus event on an HTML dialog and attempting to validate if the currently focused element is part of my "dialog" class. Check out the code snippet below: $(document).ready(() => { document.addEventListe ...

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 ...

I am experiencing import issues with ts-node/ts-jest and unable to import the necessary modules

I'm having trouble with a syntax error while trying to integrate mdast-util-from-markdown into my Jest tests for a TypeScript project. I am seeking a solution that does not involve using Babel. The code functions properly when using ts-node. Issue: ...

Unable to retrieve values from nested objects in component.html

Hey fellow tech enthusiasts, I'm currently dealing with a complex nested JSON object retrieved from an API. Here's a snippet of the object: profile : { title:"Mr", personalInfo:{ fullNames: "John Doe", id ...

Can the lib property in tsconfig.json override the target property?

Just starting out with Typescript, I have a query regarding the lib and target properties. Below is my tsconfig.json file: { "compilerOptions": { "target": "es5", "outDir": "./dist", "rootDir": "./src", "noEmitOnError": true, } } //index.ts consol ...

Pair two values from the interface

I need to extract and combine two values from an Interface: export interface CurrenciesList { currency: string; country: string; } The initial mapping looks like this: this.optionValues["currency"] = value.map(i => ({ id: i.currency, name: i.curr ...

Having difficulty importing the WebRTCAdaptor from the antmedia package stored in the node modules directory into an Angular Typescript file

An error is appearing indicating that: There seems to be a problem finding a declaration file for the module '@antmedia/webrtc_adaptor/js/webrtc_adaptor.js'. The file 'D:/web/node_modules/@antmedia/webrtc_adaptor/js/webrtc_adaptor.js' ...

Is it possible to pass a Styled Components Theme as Props to a Material UI element?

After spending 9 hours scouring the internet for a solution, I am at my wit's end as nothing seems to work. Currently, I am developing a React component using TypeScript. The issue lies with a simple use of the Material UI Accordion: const Accordion ...

Error: Unable to locate sportsRecord due to missing function

updated answer1: Greetings, I have updated the question with some detailed records and console logs for better understanding. sportsRecord = { playerTigers:[ {TigerNo: 237, TigerName: "Bird Bay Area", TigerkGroupNo: 1, isDefault: true ...

Using 'cy.get' to locate elements in Cypress tutorial

Is there a way to search for one element, and if it's not found, search for another element? cy.get(@firstElement).or(@secondElement).click() Can I use a function similar to || in conditions for this scenario? ...

How can I suggest the return type of a function that is out of my control?

When I attempt to parse a JSON-formatted string, a linter error is triggered: let mqttMessage = JSON.parse(message.toString()) // ESLint: Unsafe assignment of an `any` value. (@typescript-eslint/no-unsafe-assignment) Given that I am in control of the con ...

What is the best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...

Exploring Cypress Component Testing within a NextJS project

Could someone assist me with understanding how to utilize the cypress plugin for nextJS in order to execute Cypress Components Test package.json "devDependencies": { "@cypress/react": "^5.3.4", "@cypress/webp ...