You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Functions with intersection arguments are not always typed coherently #9514
// tl;dr: // This should give a static error, but does not.varmonkeyAnalyzer: (input: Monkey)=>void=(input: Monkey&Robot)=>{console.log(input.FurColor,input.MotorCount);}// Will definitely fail, as we can expect from the incompatible signatures of the declared type of monkeyAnalyzer and what we actually assign to itmonkeyAnalyzer(newMonkey());// Verbose exampleclassMonkey{publicFurColor: string;}classRobot{publicMotorCount: number;}classMonkeyRobotAnalyzer{publicstaticAnalyze=(input: Monkey&Robot): void=>{console.log(input.FurColor,input.MotorCount);}}classMonkeyManager{constructor(monkeyAnalyzer: (input: Monkey)=>void){monkeyAnalyzer(newMonkey());}}MonkeyRobotAnalyzer.Analyze(newMonkey());// Shows error as it shouldvarmyManager=newMonkeyManager(MonkeyRobotAnalyzer.Analyze);// No error, but should not be allowed, signature of MonkeyRobotAnalyzer.Analyze is not compatible with (input: Monkey) => void
Expected behavior:
The incompatible signatures should result in a static error
When comparing the types of function parameters, assignment succeeds if either the source parameter is assignable to the target parameter, or vice versa.
Here you are using (input: Monkey & Robot) => void as (input: Monkey) => void, and the latter is assignable to the former. So the function call just type checks.
Oh my, would it be possible to get this as a compiler flag? This led to a lot of code being faulty and in need of refactoring in a system I'm working on due to a minor mistake in the type declaration of an input parameter.
It seems that the motivation for this behavior is to enable useful hacks at the cost of type safety. Isn't typescript all (well mostly) about the opposite? A small compiler flag at least? Pretty please?
Activity
HerringtonDarkholme commentedon Jul 5, 2016
This is a by-design behavior because of bivariant function, as stated in FAQ
Here you are using
(input: Monkey & Robot) => voidas(input: Monkey) => void, and the latter is assignable to the former. So the function call just type checks.Elephant-Vessel commentedon Jul 5, 2016
Oh my, would it be possible to get this as a compiler flag? This led to a lot of code being faulty and in need of refactoring in a system I'm working on due to a minor mistake in the type declaration of an input parameter.
It seems that the motivation for this behavior is to enable useful hacks at the cost of type safety. Isn't typescript all (well mostly) about the opposite? A small compiler flag at least? Pretty please?
HerringtonDarkholme commentedon Jul 5, 2016
Please see this discussion.
#1394