Description
This is a suggestion to get rid of the inconsistency between the strictness of functions and function types.
TypeScript Version: 2.6
A function returning an interface will fail to compile if the return contains properties that are not part of the interface. This is expected:
interface X { x: number; }
function getX( ): X
{
return { x: 1, y: 2 };
}
Correctly fails with error TS2322: Type '{ x: number; y: number; }' is not assignable to type 'X'.
However, this is inconsistent with function types:
type XGetter = ( ) => X;
const getX2: XGetter = ( ) =>
{
return { x: 1, y: 2 };
}
This compiles fine, although the function shouldn't be assignable to getX2
IMO. Can this perhaps be more strict? Currently, one has to manually add the return type to the r-value:
const getX2: XGetter = ( ): X => // Added ": X"
{
return { x: 1, y: 2 }; // Will now fail here
}
While this certainly works, it makes it hard to write libraries (or simple wrappers) that enforce expected behavior, where the users shouldn't have to know to be strict about their callbacks, but rather this be enforced by the library:
// This is in a library
function getXFromFun( fn: XGetter )
{
return fn( );
}
// This is a user using the library
getXFromFun( ( ) => ( { x: 1, y: 2 } ) ); // This should fail