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?

1
  • 1
    You may find Method overloading? post on SO to be relevant to your case. Commented Aug 17, 2014 at 0:51

1 Answer 1

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 ^

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

2 Comments

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.
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

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.