Skip to content

Inherited types in callback functions #222

Closed
@arknave

Description

@arknave

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    By DesignDeprecated - use "Working as Intended" or "Design Limitation" instead

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions