Creating a Typescript interface with at least one specified type

I've recently delved into using typescript. Currently, I'm faced with a scenario where I need to import available types from backend endpoints. In one specific instance, an endpoint can support two types as parameters.

Example:

interface B extends A {
    value?: string,
    values?: string[]
}

Here, A represents the type imported from the backend, and it may have either value: string or values: string[].

Currently, I've made both properties optional in the interface B, but I believe this is not the ideal solution. How can I structure interface B so that it only contains either value or values?

Thank you.

Answer №1

If you're searching for the solution to the "either or" scenario, you'll need a concept known as a union type. These are created using the pipe | operator and signify "either this type OR that type".

Here's an illustration:

type StringOrNumber = string | number;

Alternatively:

type FooOrBar = { foo: string; } | { bar: string; };

For your specific situation:

interface IWithValue {
   value: string;
}

interface IWithValues {
   values: string[];
}

type IValueOrValues = IWithValue | IWithValues;

You can experiment with an example in the typescript playground.

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

What is the best way to organize checkboxes (either checked or unchecked) within a mat-table?

https://i.stack.imgur.com/cDQY7.png <ng-container matColumnDef="scheduled"> <th mat-header-cell mat-sort-header *matHeaderCellDef> Scheduled </th> <td mat-cell *matCellDef="let station"> ...

What is the best way to position Scroll near a mat row in Angular?

With over 20 records loaded into an Angular Material table, I am experiencing an issue where clicking on the last row causes the scroll position to jump to the top of the page. I would like the scroll position to be set near the clicked row instead. Is th ...

In Typescript, the module source is imported rather than the compilation output

I created a custom module for personal use and decided to host it on a private GitHub repository. Within the module, I have included a postinstall script that runs: tsc -d -p .. Currently, the generated .js and .d.ts files are located alongside the source ...

Building a frontend and backend using Typescript with a shared folder for seamless integration

I am currently exploring the idea of transitioning to TypeScript, but I am facing challenges in figuring out how to create a shared folder between the frontend and backend. This is the project structure that I have come up with: frontend - src -- server.t ...

When working with Typescript, it is important to correctly identify elements as checkboxes in order to avoid any red underlines when referencing

When trying to check the input type of an element, such as a checkbox in TypeScript, I encounter the issue of the 'element.checked' property being underlined in red. The code snippet below shows how I attempt to address this: element: HTMLElemen ...

Perplexed by the implementation of "require(...)" in TypeScript

After reading several blog posts, my understanding of TypeScript modules remains confusing. I have worked with three different modules (all installed via npm) and encountered varying behavior: (1) Importing and using Angular 2 from npm required me to add ...

Trigger the Angular Dragula DropModel Event exclusively from left to right direction

In my application, I have set up two columns using dragula where I can easily drag and drop elements. <div class="taskboard-cards" [dragula]='"task-group"' [(dragulaModel)]="format"> <div class="tas ...

TSLint warning: Duplicate identifier detected - 'err'

Currently facing an issue with tslint displaying the following error Shadowed name: 'err' Providing the code snippet for reference fs.readdir(fileUrl, (err, files) => { fs.readFile(path.join(fileUrl, files[0]), function (err, data) ...

How can you specify the active route in Angular?

I am curious about whether it is possible to set the active route from a script instead of just from the HTML template. Let me provide an example: @Component({ template: `<input type="button" (click)="back()" value="back" ...

Angular StrictNullChecks: "Error - object may be null"

I am encountering an issue with the 'strictNullChecks' setting in my Angular project. This has resulted in numerous errors across my templates (.html), such as: <input #inputValue type="text" (keyup.ent ...

Automate the process of triggering the "Organize Imports" command on a VSCode / Typescript project through code

Is there a way to automatically run VSCode's 'Organize Imports' quickfix on every file in a project, similar to how tslint can be run programatically over the entire project? tslint --project tsconfig.json --config tslint.json --fix I want ...

arrange the elements in an array list alphabetically by name using the lodash library

Is there a way to alphabetically sort the names in an array list using JavaScript? I attempted to achieve this with the following code: const sample = [ { name: "AddMain", mesg: "test000" }, { name: "Ballside", ...

Idiosyncratic TypeScript behavior: Extending a class with comparable namespace structure

Lately, I've been working on creating a type library for a JavaScript written library. As I was defining all the namespaces, classes, and interfaces, I encountered an error TS2417 with some of the classes. I double-checked for any issues with method o ...

Establishing a server in Node.js alongside an Angular 2 frontend by harnessing the power of Typescript

I'm looking to deploy my web application on IBM Bluemix with Angular 2 using Typescript for the frontend and Node.js for the backend. Can you advise me on how to configure the server, connect it to the frontend, and specify which transpiler I should u ...

Compiler error occurs when trying to pass props through a higher-order component via injection

Recently, I have been experimenting with injecting props into a component using a higher order component (HOC). While following this insightful article, I came up with the following HOC: // WithWindowSize.tsx import React, {useEffect, useMemo, useState} fr ...

Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end. Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpec ...

Troubleshooting issues with importing modules in TypeScript when implementing Redux reducers

Struggling to incorporate Redux with TypeScript and persist state data in local storage. My current code isn't saving the state properly, and as I am still new to TypeScript, I could really use some suggestions from experienced developers. Reducers i ...

Guide on retrieving the interface property name or key name as a string in Typescript

Currently, I am utilizing the API of Slack and encountering situations where I send JSON requests containing strings that return as property names later on. I want to create an interface where I can send one of its property names as a string and receive t ...

When compiling to ES5, TypeScript fails to remove imports

I am working on a TypeScript file that utilizes the moment library, and I need to import moment for it to compile properly. However, after compilation, the import line is still present in the compiled file, which is causing issues on my web page. Here is ...

The subscribe method in Angular TS may be marked as deprecated, but worry not as it is still

I have developed a function that retrieves new data from a service file each time it is called. Here is how the function looks: onCarChange() { this.carService.getCarData(this.selectedCar).subscribe( async (response: CarData) => { if (response?.d ...