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

Cool example of Typl's powerful inference #30

Open
getify opened this issue Feb 22, 2019 · 0 comments
Open

Cool example of Typl's powerful inference #30

getify opened this issue Feb 22, 2019 · 0 comments
Labels
cool-example Something very interesting to look at

Comments

@getify
Copy link
Owner

getify commented Feb 22, 2019

This innocently seeming code is remarkably more complex to infer, and Typl correctly reports an error like a champ (where TS and Flow do not):

var y = foo(3);
var z = "hello" + y;

function foo(x) {
	return x;
}

Here, we want the + operation to report an error because it's mixed types (string and number).

How that happens is, on the first pass, we don't know about foo(..) the function yet when we get to foo(3). So, we mark that we need to come back to it on another pass. Then, we find the function foo(..), but it doesn't have any annotated types.

On pass 2, we imply the x parameter as number from the foo(3) call. But we still don't know the return value of foo(..) to be able to imply a type for y. At the end of pass 2, we figure out the return type of foo(..) as number.

Finally, on pass 3, we can imply type number to y, and then we can validate the string + number needs to report an error!

(pass 1) ------------------------
Implying z as inferred-type 'string', at line 2, column 4
Implying foo as inferred-type 'func', at line 4, column 0
Function 'foo' signature: {"type":"func","params":[{"inferred":"unknown"}],"hasRestParam":false,"return":{"default":true,"inferred":"undef"}}, at line 4, column 0
(pass 2) ------------------------
Implying parameter x from argument, as inferred-type 'number', at line 4, column 13
Function 'foo' signature: {"type":"func","params":[{"inferred":"number"}],"hasRestParam":false,"return":{"inferred":"number"}}, at line 4, column 0
(pass 3) ------------------------
Implying y as inferred-type 'number', at line 1, column 4
Binary `+` operation, mixed operand types: type 'number' doesn't match type 'string', at line 2, column 8
Function 'foo' signature: {"type":"func","params":[{"inferred":"number"}],"hasRestParam":false,"return":{"inferred":"number"}}, at line 4, column 0
@mraak mraak added the cool-example Something very interesting to look at label Feb 23, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
cool-example Something very interesting to look at
Projects
None yet
Development

No branches or pull requests

2 participants