-
Notifications
You must be signed in to change notification settings - Fork 13.1k
Description
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()); // ERRORSo 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?