Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
datokrat opened this issue Aug 29, 2016 · 0 comments
Closed

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

datokrat opened this issue Aug 29, 2016 · 0 comments
Labels
Fixed A PR has been merged for this issue

Comments

@datokrat
Copy link

datokrat commented Aug 29, 2016

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?

@mhegazy mhegazy added the Fixed A PR has been merged for this issue label Jan 21, 2017
@mhegazy mhegazy added this to the TypeScript 2.2 milestone Jan 21, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

2 participants