Encountering an unusual edge case with the TS compiler regarding type inference. Surprisingly, the code snippet below (with commented lines intact) should trigger a compile error, but it doesn't.
interface IReturned {
theField?: string;
}
interface IFactory {
(): IReturned;
}
var factory : IFactory = function () /* : IReturned */{
return {
BROKEN: 'ERROR'
}
};
var instance = factory();
// instance.BROKEN;
Ideally, the return type of the factory function should be inferred as IReturned, making it invalid to return an object literal with extra fields, such as setting the "BROKEN" property.
If the function is explicitly annotated with IReturned as its return type, this behavior is enforced. The type of the "instance" variable is correctly inferred, and accessing the "BROKEN" field below triggers an error.
Is there something missing here? Is there a workaround to achieve the desired result without redundant type definitions?