Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Function types are not as strict as types of functions #20859

Closed
grantila opened this issue Dec 22, 2017 · 3 comments
Closed

Function types are not as strict as types of functions #20859

grantila opened this issue Dec 22, 2017 · 3 comments
Labels
Duplicate An existing issue was already created Fix Available A PR has been opened for this issue

Comments

@grantila
Copy link

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
@DanielRosenwasser
Copy link
Member

I think this is #241?

@grantila
Copy link
Author

Yeah more or less, I didn't see that.

@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@microsoft microsoft locked and limited conversation to collaborators Jul 3, 2018
@typescript-bot typescript-bot added the Fix Available A PR has been opened for this issue label Sep 2, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created Fix Available A PR has been opened for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants