0

I'm having a hard time reconciling what is going on with the following file:

interface T {
  _t(chunk: Array<string>): void;
  _t(chunk: string): void;
}

class TT implements T {
  _t(chunk: string): void {}
}

When I try to compile it I get the following error message:

Types of property '_t' of types 'TT' and 'T' are incompatible:
    Call signatures of types '(chunk: string) => void' and 
      '{ (chunk: string[]): void; (chunk: string): void; }' are incompatible:
        Type 'String' is missing property 'join' from type 'string[]'.

That's fine so that means I should be able to get around the issue by explicitly specifying the object type of the property right?

interface T {
  _t(chunk: Array<string>): void;
  _t(chunk: string): void;
}

class TT implements T {
  _t: {
    (chunk: string): void;
    (chunk: Array<string>): void;
  } = function(chunk) {};
}

Except the problem is now when I compile with --noImplicitAny I get the following error message:

error TS7012: Parameter 'chunk' of lambda function implicitly has an 'any' type.

It seems like no matter what I do I lose because if I'm careful with the type specifications on the interface and spell out everything then I can't specialize the implementation to only 1 type. The problem is that there are .d.ts files out there that do exactly this and if I want the compiler to find all any types because I want to be as explicit as possible I have to take out specifications from .d.ts files to be able to both implement interfaces and specialize implementations in subclasses. This seems like a bug. How do I resolve this?

David K.
  • 6,153
  • 10
  • 47
  • 78
  • 1
    You may find [Method overloading?](http://stackoverflow.com/questions/12688275/method-overloading) post on SO to be relevant to your case. – PM 77-1 Aug 17 '14 at 00:51

1 Answers1

2

Just type it chunk:any:

interface T {
  _t(chunk: Array<string>): void;
  _t(chunk: string): void;
}

class TT implements T {
  _t: {
    (chunk: string): void;
    (chunk: Array<string>): void;
  } = function(chunk:any) {};
}

// Safety: 
var t = new TT();
t._t(''); // okay
t._t([]); // okay
t._t(true); // Error

Note it doesn't decrease your type safety ^

basarat
  • 261,912
  • 58
  • 460
  • 511
  • Ya, that's what I ended up doing. Didn't know that was allowed although it is a bit confusing to have to give it type `any`. – David K. Aug 17 '14 at 04:04
  • 1
    Its needed because *inside* the function body you could do `chuck.foo` and the compiler wouldn't give you an error because it thinks its `any`. So you need to be explicit if you use `--noImplicitAny` – basarat Aug 17 '14 at 04:51