JSMonk / hegel

An advanced static type checker
https://hegel.js.org
MIT License
2.09k stars 59 forks source link

is it safe/possible to infer tuples in return statement? #303

Open mohsen1 opened 4 years ago

mohsen1 commented 4 years ago
function makeTuple(x,y) { return [x,y] }
const makeTuple(1,2); // currently `Array<number>`. Hoping for `[1, 2]`

I wish this was automatically inferred instead of defaulting to Array<number>. Is there a theroical limit to how this return type can be inferred?

It is possible to annotate the types with generics

function makeTuple<X, Y>(x: X, y: Y): [X, Y] { return [x, y] }

const tuple = makeTuple(1, 2);
Soremwar commented 4 years ago

If it were in my hands I would wait for ECMA to implement tuples instead of trying to port over TypeScript ones (instead of emulating immutable values you get actual immutable values, plus some interesting value checks)

This one would likely land next year

https://github.com/tc39/proposal-record-tuple

mohsen1 commented 4 years ago

That's fair @Soremwar but I think it is in the sprit of Hegel to infer the type of [1,2] as [1,2] instead of Array<number>. TypeScript infers type of foo as number in const foo = 1 but Hegel infers 1.

Soremwar commented 4 years ago

Yeah, my idea would make that inference happen as well but instead of supporting tuples through array syntax it would make that kind of analysis over tuple syntax

Example:

const a = [1, 2] // a: number[]

const b = #[1, 2] // b: [1, 2]

Why is it preferable to make it this way?

I'm gonna jump the gun and say inference over an array that can contain thousands of mutable values might not be a good idea

JSMonk commented 4 years ago

I think the answer is "Yes". Because we can use some heuristics to understand how developers use the value (as Array or as a tuple). So, I will try to implement it soon as a draft. Thank you for the proposal :3