Skip to content

Inference fails for return-type of type-union between class and generic type #2211

Closed
@mindplay-dk

Description

@mindplay-dk

Type inference seems to fail when the return-type is a union between a class and a generic type.

I was hoping to use this pattern to be able to decorate an object (not a class) with traits/behaviors on a per-instance basis, in a type-safe manner, something along the lines of Scala's with operator.

Best explained by example:

class Fud {}

interface Decorated {
    foo(): string;
}

function decorate<T>(object: T) : T|Decorated {
    object['foo'] = function () {
        return 'Hello';
    };
    return <T|Decorated> object;
}

var test = decorate(new Fud());

console.log(test.foo()); // ERROR

So anything that goes through the decorate() function comes out decorated with a new interface, which is made possible using a union between a variable type and some interface.

Hovering over the call to decorate(), the return-type is correctly reported as Decorated | Fud - however, when the result is assigned to the test variable, the inferred type is Fud, and the attempt to call test.foo() generates the error "property foo does not exist on type Fud".

Am I missing something? Is there some reason this shouldn't work?

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