Implementing the same function twice but with varying argument types

Within my TypeScript class, I have the following two methods:

authorize(resource: any, requirement: Requirement) : boolean {
  return false;
}

authorize(resource: any, policy: Policy) : boolean {
  return false;
}

Despite the different argument types (policy and requirement), an error is occurring:

Duplicate function implementation.

I'm puzzled as to why this duplication is happening. Any insights on how to resolve this issue?

What would be the best approach to tackle this problem?

Answer №1

In TypeScript, there is a feature called function overloading which allows you to define multiple functions with the same name but different parameter types and return type. However, it is important that the number of parameters remains the same.

add(a: string, b: string): string;

add(a: number, b: number): number;

add(a: any, b: any): any {
  return a + b;
}

I hope this explanation helps you understand function overloading in TypeScript better. For further information, you can visit this link.

Answer №2

To achieve this functionality, you can utilize an interface.

Start by creating an interface that both Policy and Requirement classes will implement:

interface IAuthorizeParam {
    myValue: string;
}

class Policy implements IAuthorizeParam {
    myValue: string = 'Policy';
}
class Requirement implements IAuthorizeParam {
    myValue: string = 'Requirement';
}

class Example {
    authorize(resource: any, authParam: IAuthorizeParam): boolean {
        console.log(authParam.myValue);
        return false;
    }
}


const x: Example = new Example();

x.authorize({}, new Policy());
x.authorize({}, new Requirement());

This setup allows the authorize method to work with any class that implements the IAuthorizeParam interface.

Please note that IAuthorizeParam is just a placeholder name in this example.

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

Tips on exporting a basic TypeScript class in an Angular 4 module

I am facing a challenge with packaging a TypeScript class as part of an Angular module for exporting it as a library using ng-packagr. For instance, here is my class definition - export class Params { language: string ; country: string ; var ...

Having trouble establishing a connection with the SQL Server through my VS Code extension in node.js

Currently working on a VS Code extension and facing challenges in retrieving data from an SQL Server database. Despite trying multiple examples, none of them seem to be effective for me. const Connection = require('tedious').Connection; ...

Navigate to the Authorization Endpoint upon Initial Angular Load

Is there a way to redirect to the authorization endpoint before loading the Angular components and HTML? Can I use the CanActivate auth guard on my main app component for this purpose? I have implemented an auth guard in my Angular project, but it seems t ...

Angular 5 throwing an error - trying to access a property that is undefined

In my form, each div contains a label, checkbox, and input field. When the menu is opened, all checkboxes are initially unchecked, disabling all input fields. You can then enable an input field by checking its corresponding checkbox. I attempted to implem ...

Why is there an error when trying to assign Type '{}' in generics typescript?

I'm having trouble understanding why this code is causing an error. The error message says - Type '{}' is not assignable to type 'Keys<T>'. type Keys<T extends string|symbol>={ [key in T]: string; }; const foo = < ...

The logic behind regular expressions

Currently working on building a web application with Angular 6 and I have a query: I'm in the process of developing a custom input component (specifically for text inputs) like so: @Component({ selector: 'input-text', templateUrl: &apos ...

Angular TextInput Components don't seem to function properly when dealing with arrays

I am trying to create a collection of text input components with values stored in an array. However, when using the following code, the values seem to be placed incorrectly in the array and I cannot identify the bug. <table> <tr *ngFor="let opt ...

Angular component name constraints - 'the selector [your component name] is not permissible'

When trying to generate a component using the Angular 6 CLI (version 6.0.7), I encountered an issue. After typing in ng g c t1-2-3-user, I received an error message stating that the selector (app-t1-2-3-user) is invalid. I wondered if there was something ...

Typescript enhances the functionality of the Express Request body

I need help with the following code snippet: const fff = async (req: express.Request, res: express.Response): Promise<void> => {...} How can I specify that req.body.xxx exists? I want it to be recognized when I reference req.body.xxx as a propert ...

Using Javascript or Typescript, update the view to display the user's name instead of their user ID

I own a collection of car models. Each individual car is associated with a unique userid. Furthermore, each user model contains both a userid and a corresponding username. In my view, I aim to showcase all of my car models alongside their respective usern ...

Error display in Elastic Apm Rum Angular implementation

Having some issues with incorporating the @elastic/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f5948598d8878098d8949b9280999487b5c7dbc4dbc4">[email protected]</a> package into my project. Angular is throwing console ...

What is the best way to schedule a function to run at a specific time using timestamp data from MongoDB?

Imagine I have a scenario where I need to store timestamps in my MongoDB database, each timestamp representing a time when a specific function should be executed. Given that I'm new to backend development, I'm unsure about the correct approach f ...

Limit the valid input values for the number within the range of 1 to 3

HTML code <div class="col-sm-12"> <input class="form-control form-control-md" [ngModel]="item.threshold" placeholder="Set Threshold" formControlName="threshold" type="text"> <span class="text-danger text-small block" *ngIf="editT ...

Guide to displaying loading progress during server response delay in React with TypeScript

I need to find a way to update the loading state to false once the server responds. The challenge is that the response occurs in one component, while the progress bar is located in another. To illustrate the scenario: const Form: React.FC = () => { ...

Practical application of generics in TypeScript

I'm struggling to understand the practical use of generics in typescript. interface ICustomer { name: string; age: number; } function CalculateAverageAge<c extends ICustomer>(customer1: c, customer2: c): number { return (customer1.age + ...

Guide to summing the values in an input box with TypeScript

https://i.stack.imgur.com/ezzVQ.png I am trying to calculate the total value of apple, orange, and mango and display it. Below is the code I have attempted: <div class="row col-12 " ngModelGroup="cntMap"> <div class="form-group col-6"> ...

Sorting data with TypeScript using the Merge Sort algorithm

After spending some time working on a merge sort implementation in TypeScript, I noticed that half of my array seems to be missing from the final result. Can someone with more experience shed some light on why this might be happening? Source: function mer ...

Parsing errors occurred when using the ngFor template: Parser identified an unexpected token at a specific column

In my Angular CLI-built application, I have a component with a model named globalModel. This model is populated with user inputs from the previous page and displayed to the user in an HTML table on the current page. Here's how it's done: <inp ...

Creating a TypeScript interface for React component props

import IntroductionArea from "../components/IntroductionArea"; interface AppSegment { path: string; component: React.FC<any> | React.LazyExoticComponent<React.FC<any>>; properties?: React.ComponentProps<any>; } exp ...

The absence of the 'profileStore' property is noticed in the '{}' type, which is necessary in the 'Readonly<AppProps>' type according to TypeScript error code ts(2741)

I'm currently using MobX React with TypeScript Why am I getting an error with <MainNote/>? Do I just need to set default props? https://i.stack.imgur.com/5L5bq.png The error message states: Property 'profileStore' is missing in typ ...