Why does TypeScript allow overloading return type as 'any' when implementing interfaces

Viewed 110

I am trying to determine why TypeScript allows you to overload the return type of a function to the type 'any' from a more specific type when implementing an interface.

In my case I am working in Angular and am injecting the implemented class.

My environment:

Visual Studio 2017

Angular Version 1.5.5

TypeScript Version 2.1.5

The following code compiles without any issue:

export interface IFoo {
    thing: (parameter: number) => string;
}

export class BarService implements IFoo {
    public thing = (parameter: number): any => {
        return { "whatever": parameter };
    }
}
angular.module("FooBar").service("barService", BarService);

So now when I attempt to consume the IFoo interface and am expecting a string to be returned from the 'thing' function call the compiler actually allows it to happen!

export class Whatever {
    public foo: IFoo;
    public myString: string;

    static $inject = ["barService"];
    constructor(barService: IFoo) {

        this.foo = barService;

        this.myString = this.foo.thing(0);
    }
}

It seems that TypeScript should fail to compile when the return type is overloaded with type 'any' because consumers of the interface are expecting a strongly typed object.

3 Answers
Related