Skip to content

Implement "this" type for intersection and union types #10591

Closed
@datokrat

Description

@datokrat

TypeScript Version: 1.8.0

It seems that polymorphic 'this' types don't apply as expected to intersection and union types.

Motivating Example: Lightweight Mixins

This example was forked from the proposal on polymorphic 'this' types considering "lightweight mixin"s. Unfortunately, the model can only be extended once because 'this' only includes "real" class extensions and no union type extensions as shown in the example. That's why the current implementation doesn't help us with the specified example.

interface Model {
  extend<T>(t: T): this & T;
}

interface NamedModel extends Model {
  name: string;
}

declare function createNamedModel(): NamedModel;

var extendedModel = createNamedModel().extend({
  age: 30
}).extend({
  job: "programmer"
});
extendedModel.name; // valid
extendedModel.job; // valid
extendedModel.age; // error: Property 'age' does not exist because type is NamedModel & { job: string }

Suggestion

I suggest allowing the following:

interface A {
    getThis(): this;
}

let extended: A & { y: string };
extended.getThis().y;

This would require to assign intersection and union types to "this" instead of only superclasses of A. As far as I can see, this should not be too complicated/invasive, is it? I could not find any explicit decision against this feature, so maybe it's kind of a bug?

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions