Hacker News new | ask | show | jobs
by curryhoward 3149 days ago
Just as an example, this program type checks in TypeScript but crashes at runtime:

    class Dog {
    }

    class Greyhound extends Dog {
        doGreyhoundThing(): void {
            console.log("I am a greyhound!");
        }
    }

    class Poodle extends Dog {
        doPoodleThing(): void {
            console.log("I am a poodle!");
        }
    }

    function f(g:(Dog) => void) : void {
        let hound: Greyhound = new Greyhound();
        g(hound);
    }

    function h(p: Poodle): void {
        p.doPoodleThing();
    }

    f(h);
`f(h);` would be a type error if function types were contravariant in their argument types. TypeScript made the unsound choice to let function types be bivariant in their argument types, which the authors claim is justified for practical reasons. More info here: https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-fun...
2 comments

They added contravariant functions in 2.6 using the compiler flag --strictFunctionTypes as described in this PR https://github.com/Microsoft/TypeScript/pull/18654
When I was student (1992), a friend noticed exactly the same issue in the eiffel language. They answered also that the incorrect check was more practical.