Jordi
Jordi

Reputation: 23277

Typescript: duplicate function implementation message

I've created these two static factory methods into my class:

export class ConstantImpl<T> {
    public static create(b: Boolean): Constant<Boolean> {
        return new ConstantImpl<Boolean>(b);
    }

    public static create(i: Number): Constant<Number> {
        return new ConstantImpl<Number>(i);
    }
}

However, I'm getting this compilation error message:

Duplicate function implementation.

Any ideas?

Upvotes: 3

Views: 6155

Answers (2)

jcalz
jcalz

Reputation: 330216

As @cartant suggested, you can use overloads in TypeScript. They have a single implementation but multiple signatures. You can read about it in the handbook to see how to make the signatures and implementation play well together. In your case, you can do something like this:

export class ConstantImpl<T> {
  // guessing at your constructor
  public constructor(public val: T) {

  }

  public static create(b: boolean): Constant<boolean>;
  public static create(i: number): Constant<number>;
  public static create(v: boolean | number): Constant<boolean | number> {
        return new ConstantImpl(v);
    }
}

This will only allow ConstantImpl.create() to accept a boolean or a number value, and it will reject everything else. Note that I didn't have to inspect the type of v to see if it is a boolean or a number, nor did I have to manually specify the value of T in the call to the ConstantImpl<T> constructor, because the constructor infers the value of T from the argument you pass in.

And really, in that case, it makes me wonder why you care to restrict ConstantImpl.create() to only accept boolean and number values. Why not go the full generic route instead?

  // accept any type
  public static create<T>(v: T): Constant<T> {
    return new ConstantImpl(v);
  }

Hope that helps; good luck.

Upvotes: 2

CharybdeBE
CharybdeBE

Reputation: 1843

As said in my comment overloading is not implemented in typescript as it is in JAVA for example

You can try something like that

export class ConstantImpl<T> {
    public static create(a: any): Constant<any> {
        if(typeof a == "Boolean")
           return ConstantImpl.createBoolean(a);
        if(typeof a == "Number")
           return ConstantImpl.createNumber(a);
    }
   public static createBoolean(b: Boolean): Constant<Boolean> {
    return new ConstantImpl<Boolean>(b);
   }

}

ps: I do not have tested/compiled this specific function it is just an example type can be present

Upvotes: 0

Related Questions