Hacker News new | ask | show | jobs
by squiggleblaz 2476 days ago
The compiler should be capable of inferring the type as far as reasonably possible. But it should be an error to not specific the types of top level functions and class methods.

This way, when you write

    const f = (a, b) => a + b
the compiler can tell you to write:

    const f => <T extends number|string>(a: T, b: T): T => a + b
or

    const f : <T extends number|string>(a: T, b: T) => T
            = (a, b) => a + b
This would be effectively like GHC's typeholes, where the compiler will tell you what to write when you say

    f :: _
    f a b = a <> b
except that rather than being an optional step by a developer, it's a mandatory standard.

(Well, I don't think typescript infers that type for that function, but whatever it actually infers, that's what should be there in the error message.)

1 comments

I don't think typeholes is necessary for that feature. It suffices to just use type check up to the function signature. If I write:

    fn foo() { 42 } 
in Rust, I get an error that says that `i32` (the type of `42`) is not of type `()` (unit), which is the return type of `foo`. So I can just change it to:

    fn foo() -> i32 { 42 } 
instead. The same applies for generics, if I write:

    fn bar<T>(x: T, y: T) -> T { x + y }
I get the precise error that T does not implement the `Add<T>` trait. In this case the error is precise because there is only a trait in scope that supports `+`, but once there are many traits that would fit, which is rare, the compiler suggests some (often all of them). With that error I can just change that to:

    fn bar<T: Add>(x: T, y: T) -> T { x + y }
This is all done through local type inference within the function.