Is there an interface that combines features from two interfaces while also introducing new properties?

Action must include the attributes children, size?, and variant?.

Action should also feature either Button or Link.

How do I accomplish this?

This is my best attempt:

interface Button {
    action: () => void;
    href?: never;
}
interface Link {
    href: string;
    action?: never;
}

interface Action extends Button | Link {
    children: string;
    size?: 'large' | 'small';
    variant?: 'secondary';
}

Error:

[tslint] Forbidden bitwise operation

The main functional requirement I have is to create a type or interface with certain properties along with either action or href, but not both simultaneously.

Answer №1

Unfortunately, an interface cannot extend a union type. However, you can use an intersection type instead:

interface Button {
    action: () => void;
    href?: never;
}
interface Link {
    href: string;
    action?: never;
}

type Operation =  (Button | Link) & {
    data: string;
    size?: 'big' | 'small';
    variant?: 'primary';
}

let op1: Operation = {
    href: "",
    data: "",
    size: "big"
}


let op2: Operation = {
    action: () => { },
    data: "",
    size: "big"
}


let op3: Operation = { // error
    href: ""
    action: () => { },
    data: "",
    size: "big"
}

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 steps should be taken if a typings (or tsd) file cannot be found?

After reading through the TypeScript handbook, I realized that I couldn't find the solution to my problem. What are my options if I'm using a library without existing typings? The first option is to create the typings file myself, but I'm ...

I'm encountering issues with the Cordova social share plugins not functioning properly within my Angular2 application

Having trouble navigating the ins and outs of using social share plugins. SocialSharing-PhoneGap-Plugin Every time I attempt to call on this plugin, an undefined error pops up. Here is a snippet of my code. window.plugins.socialsharing.share("test"); Aft ...

Error encountered in jquery.d.ts file: Unresolved syntax issue

I am currently in the process of transitioning my jQuery project into a Typescript project. I encountered an issue when attempting to include the jQuery typings from the DefinitelyTyped Github by using the following method: ///<reference path="../../ty ...

Accessing one controller from another module in AngularJS using TypeScript is a common challenge that many developers face. In this article, we

// inside engagement.component.ts: class EngagementMembersController { alphabetic: Array<string> = 'abcdefghijklmnopqrstuvwxyz'.split(''); constructor() {} export const EngagementSetupMember: IComponentOptions ...

Images are failing to load in Ionic 3

Currently working on developing an Ionic application and troubleshooting the use of the camera native plugin. The script functions flawlessly in a fresh project, but encounters issues within the current project environment. Initially suspected a problem w ...

Issue with npm resolution due to package requiring another third-party dependency

I'm encountering an issue with a requirement and I'm hoping for some assistance. I currently have a package called @unicoderns/orm that relies on mysql, which can be found at https://github.com/unicoderns/ORM Now I'm working on developing ...

The proper method for defining a nullable state in React when utilizing the useState hook

I'm struggling to figure out how to properly type the useState function as it returns a tuple. I need to set null as the initial value for email, meaning I can't use an empty string. The setEmail function is used to update the email state value, ...

Creating a nrwl/nx workspace with Angular Universal and encountering a typing problem in Cypress configuration

TL;DR When I run yarn webpack:server, I encounter the error message Cannot find name 'cy'. Example repository: Branch displaying error Error Explanation Hello, I am currently in the process of setting up a minimal viable product project to ...

Achieve form display and concealment with a single click using angular and jQuery, incorporating smooth animations

I am looking to create a button that will show and hide a form. Here is the form I have created : <button type="button" (click)="ShowAndHide()" class="AddCatBtn">show and hide </button> <div class="AddCategory"> <div class="for ...

Encountered an issue trying to invoke a method within a method in the controller while using Node.js, Express,

I am facing an issue with two classes in my project: authenticationRoutes.ts and authenticationController.ts. In the authenticationRoutes file, I am calling the 'authenticationController.test' method, which in turn calls the 'authenticationC ...

Discover how TypeScript's strictNullChecks feature can help you identify null values with ease in your functions

Since Javascript often requires me to check if a value is `!= null && != ''`, I decided to create a function that checks for empty values: const isEmpty = (variable: any, allowEmptyString?: boolean): boolean => { return variable == null | ...

Securing your React app with private routes and context-based authentication

I'm currently working on implementing basic authentication for a React+Typescript application using private routes and context. In my setup, I have a login component with a button that toggles a boolean variable authenticated in the context to true up ...

Storing the typeof result in a variable no longer aids TypeScript in type inference

Looking at the code snippet below: export const func = (foo?: number) => { const isNumber = typeof foo === 'number'; return isNumber ? Math.max(foo, 0) : 0; }; A problem arises when TypeScript complains that you cannot apply undefined to ...

What is the best way to send variables to a proxy server URL?

Is there a way to pass specific variables to my proxy in order to make API calls with customized parameters, similar to the scenario outlined below? This is how my proxy configuration appears: { "/darksky/*": { "target": "https://api.darksky.net/ ...

Jest and Typescript: A guide to mocking the Date object

Is there a way to mock a date object for all unit test cases in TypeScript? I have tried various JavaScript references, but they are not working due to type errors. Can someone offer a solution to resolve this issue? // Testing sampleMethod() describe(&ap ...

Unable to remove or cut out a row from JSON

I'm attempting to eliminate a user from a blacklist feature. The goal is to remove the user from the list, splice out the JSON row, and update the mat-table in Angular. My attempt using delete this.blacklistGroupTable[i] does not alter the JSON objec ...

Unable to set the default value for mat-selects

When working on the edit page, I am using patchValue to set the default value for my form. The JSON data is storing correctly, but the mat-select default value is not being set. What could I be doing wrong? I tried setting it with "[value]="item.name"", w ...

Tips on utilizing JavaScript to retrieve all HTML elements that have text within them, then eliminating the designated element and its descendants

Simply put, I am looking to extract all the text-containing elements from the HTML and exclude specific elements like 'pre' or 'script' tags along with their children. I came across information suggesting that querySelectorAll is n ...

Tips for updating a JSON object value in Node.js

Storing a JSON object in a JSON file is important for passing data during an API call. To update the object, replace "it-goes-here" with the following {} block. Newly updated data: { "parenturl":"xxx.com", "user ...

Tips for sorting an array of objects by multiple keys while maintaining the order of each key that comes before

I am looking to create a versatile function that can organize an array of objects based on specified keys, while maintaining the order of previous keys. Here is a sample scenario: const input = [ { a: 'aardvark', b: 'bear', c: 'c ...