A script object must only permit one property at a time

I am unfamiliar with TypeScript and I have an object named obj with 3 properties: a, b, c. However, it is important to note that b and c cannot exist together in the same object. So, my object will either be:

obj = {
    a: 'xxx',
    b: 'xxx'
}

or

obj = {
    a: 'xxx',
    c: 'xxx'
}

How can I properly define the type of obj in TypeScript?

Answer №1

Typescript serves a different purpose than what you are trying to achieve, as it allows you to define the structure of your objects but not the relation you desire.

There are two possible approaches to solving this issue. Firstly, you can define two types and specify that your final object is either type A or type B:

const myObj: typeA | typeB;

In typeA, you would define properties a and c, while in typeB, you would define properties a and b.

Alternatively, you could approach it this way:

You define

obj = {
  'a': string,
  'b'?: string,
  'c'?: string
}

You make both parameters optional and handle all logic checks in your component or .ts file.

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

Encountering an issue with compiling Angular due to a Type Inference error

interface Course { name: string; lessonCount: number; } interface Named { name: string; } let named: Named = { name: 'Placeholder Name' }; let course: Course = { name: 'Developing Apps with Angular', lessonCount: 15 }; named = ...

Potential Null Object in Typescript Mongoose: A Concern

Encountering an issue while attempting to locate my user model: Object is possibly 'null'. I would like to find a solution that does not involve suppressing TypeScript's strict rule. const { email, password } = req.body; const user = awai ...

Problem with RxJS array observable functionality not meeting expectations

I am struggling with an Angular service that contains an array of custom objects and an observable of this array. An external component subscribes to the observable but does not respond when the list is modified. Additionally, the mat-table, which uses the ...

Discover the simple steps to include row numbers or serial numbers in an angular2 datagrid

Currently, I am utilizing angular2 -datatable. Unfortunately, I am facing an issue where the correct row numbers are not being displayed in their corresponding rows. Whenever a user moves to the next page using the paginator, the datatable starts countin ...

Guide on setting up multiple Axios instances in NestJS

I'm in the process of migrating an existing Express application to NestJS. Currently, I have a configuration file where I define multiple axios instances for each microservice: export const writeModelApi = axios.create({ baseURL: getWriteModelApiUrl ...

What is the process for implementing a new control value accessor?

I have a directive that already implements the ControlValueAccessor interface (directive's selector is input[type=date]) and now I need another directive that also implements ControlValueAccessor with the selector input[type=date][datepicker] - let&ap ...

Verifying callback type in Typescript based on another argument's validity

There is a JavaScript function that I am working with: const fn = (cb, param) => { cb(param); }; This function is meant to be called in two ways within TypeScript: const cb0 = () => {}; fn(cb0); const cb1 = (param: string) => { }; fn(cb1, &a ...

Using JSDoc with "T extending Component"

get_matching_components<T extends Component>(component_type_to_return: { new (doodad: Doodad): T }): T[] { return this.components.filter(component => component instanceof component_type_to_return) } In TypeScript, I created a method to retrie ...

What are some ways to make autorun compatible with runInAction in mobx?

Currently delving into the world of mobx and runInAction, facing a challenge in comprehending why autorun fails to trigger my callback in this particular scenario: class ExampleClass { // constructor() { // this.exampleMethod(); // } ...

Image paths becoming unresponsive following package upgrades

My Angular2 application was originally built using angular-cli (v 1.0.0) and webpack2. Within a component, I had the ability to reference an image like so: <div class="country-flag"> <img [src]="src/assets/flags/32/jp.png" [width]="flagIconSiz ...

Master the Art of Scrolling Lists in Ionic 2

I am currently using Ionic2 for my project. One of the challenges I'm facing is scrolling to the top of a list when a specific event, called messageSend, occurs. Let me show you the code for this: <ion-content padding class="messages-page-conten ...

The combination of Object.keys() and the find function

Having trouble figuring out why I'm getting an error when attempting to use ES6 .find on the following data in order to retrieve the record with id number 3. { {id:10,title:'Dairy & Eggs'} {id:7,title:'Laundry & Household'} {id ...

Ways to pass a class list from a client to a webmethod using AJAX

I have a list of client-side classes in TypeScript that I need to send to a web method. Here is my TypeScript code: class MakeReportData { LocalName: string; FldSi: number; ViewSi:number; TypeName:string ; CheckBoxshow :boolean ; ...

Using InjectionToken within an Angular APP_INITIALIZER function

I am currently working on implementing an APP_INITIALIZER in my Angular 10 project. The factory function I'm using has multiple dependencies, one of which is an InjectionToken<string>. However, I have encountered an issue when trying to inject i ...

What is the best way to connect input values with ngFor and ngModel?

I am facing an issue with binding input values to a component in Angular. I have used ngFor on multiple inputs, but the input fields are not showing up, so I am unable to push the data to subQuestionsAnswertext. Here is the code snippet from app.component ...

Issue with extending mongoose.Document properly in NodeJS and TypeScript using a custom interface with mongoose

I recently started learning Typescript and tried to follow this guide to help me along: After following the guide, I implemented the relevant code snippets as shown below: import { Document } from "mongoose"; import { IUser } from "../interfaces/user"; ...

Having trouble resolving TypeScript TS2322 error with Context API + useState hook in your React App?

Currently, I am working on a React Typescript project that utilizes the Context API to pass down a useState hook. export const AppContext = React.createContext(null); function App() { const [value, setValue] = React.useState(3); return ( <Ap ...

The Angular Material Table is reporting an error: the data source provided does not conform to an array, Observable, or DataSource

Having some trouble with an Angular Material table, as I'm encountering an error preventing me from populating the grid: Error: Provided data source did not match an array, Observable, or DataSource search.service.ts GridSubmittedFilesList: IGridMo ...

React Component Fails to Refresh After Redux Modifications

I've recently started learning about React and Redux, and I've been trying to solve a particular issue for the past few days. The problem I'm facing is that my React component doesn't re-render when Redux updates. Despite seeing the st ...

What is the process for testing an iframe and retrieving all of the response headers?

I'm currently working on a web application that can display URLs in an iframe. However, I also want to be able to test the URL before showing it in the iframe. The goal is to wait for a response and only display the iframe if there are no errors or if ...