3 ms·
Just as an example, this program type checks in TypeScript but crashes at runtime: class Dog { } class Greyhound extends Dog { doGreyhound
by curryhoward 9y 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-function-parameters-bivariant https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-fun...
- besquared 9y agoThey added contravariant functions in 2.6 using the compiler flag --strictFunctionTypes as described in this PR https://github.com/Microsoft/TypeScript/pull/18654 https://github.com/Microsoft/TypeScript/pull/18654
- reacweb 9y agoWhen 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.