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 with empty object type parameter assignable to functions accepting more specific type #16971

Closed
SimonCJacobs opened this issue Jul 6, 2017 · 2 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@SimonCJacobs
Copy link

TypeScript Version: 2.4.1

This code shows the error that isn't picked up:

var numToString: ( x: number ) => string
var objToString = ( x: {} ) => x.toString();
numToString = objToString; // No compiler error, but should be: Type '{}' is not assignable to type 'number'
@kitsonk
Copy link
Contributor

kitsonk commented Jul 6, 2017

Event with weak type detection in 2.4.1 an empty object {} in a argument position essentially equates to any. You would need something else, like object or { [key: string]: value; } to make it not assignable. I am not 100% sure of the inner workings of why this is with the type system, but it has to do with arguments being checked in a co-variant manner, I believe.

@ghost
Copy link

ghost commented Jul 6, 2017

{} is the type of all values except null and undefined. So, const x: {} = 0; is valid.
Since objToString will accept a number, it's valid to use objToString where a numToString is expected.
Unfortunately, it's not valid to assign objToString = numToString, since numToString can't accept non-numbers but objToString is supposed to; but TypeScript will allow it because functions are checked bivariantly.
See also: #10717, #12498, #9825, #16735, #14973

@mhegazy mhegazy added the Needs Investigation This issue needs a team member to investigate its status. label Aug 29, 2017
@DanielRosenwasser DanielRosenwasser added Working as Intended The behavior described is the intended behavior; this is not a bug and removed Needs Investigation This issue needs a team member to investigate its status. labels Aug 29, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

4 participants