Inherited types in callback functions · Issue #222 · microsoft/TypeScript (original) (raw)
Typescript is too lenient when accepting sub-classes in inherited types. For example:
interface Base { baseField: string; } interface Child extends Base { childField: number; }
var test = function (callbackfn: (value: Base) => void): void { callbackfn({baseField: ""}); };
var callTest = function() { test(function (value: Child) { console.log(value.childField); }); };
should not compile, as callbackfn
requires a Base, not a Child. It is not correct that value is a child. If Child does not extend Base, then this causes a compile error as expected. However, if we add no explicit hierarchy between the classes, but change the example to
interface Base {
baseField: string;
}
interface Child {
baseField: string;
childField: number;
}
var test = function (callbackfn: (value: Base) => void): void { callbackfn({baseField: ""}); };
var callTest = function() { test(function (value: Child) { console.log(value.childField); }); };
then the code still compiles. Both of these are errors that should hopefully be caught at compile time. It looks like typescript only checks to see if a callback parameter is valid if the classes have common members. This should be changed to a subset.