2

In typescript I have the following methods in a class:

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

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

But I get the following error:

Duplicate function implementation.

Why is it duplicated if the arguments have different types, e.g., policy and requirement?

How to solve this?

1
  • 1
    try authorize(resource: any, requirement: Requirement | Policy) : boolean Commented Nov 19, 2019 at 11:10

2 Answers 2

3

TypeScript provides the concept of function overloading. You can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same.

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

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

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

Hope it helps you to understand. For more references go Here

Sign up to request clarification or add additional context in comments.

Comments

3

You can use interface to do this.

Create an interface that Policy and Requirement implements like

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());

Using this authorize can use all class that implements IAuthorizeParam.

Ps.: IAuthorizeParam is only an example name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.