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

Bug: this type not allowed in constructor #8791

Closed
nin-jin opened this issue May 24, 2016 · 3 comments
Closed

Bug: this type not allowed in constructor #8791

nin-jin opened this issue May 24, 2016 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@nin-jin
Copy link

nin-jin commented May 24, 2016

class X {
    foo = 1
    constructor( setup? : ( obj : this ) => void ) {
        if( setup ) setup( this )
    }
}

var x = new X( obj => {
    obj.foo = 2 // Ok, allowed
    // obj.bar = 3 // Ok, not allowed
} )

A 'this' type is available only in a non-static member of a class or interface.

@jeffreymorlan
Copy link
Contributor

Exposing this to outside code from a constructor is an anti-pattern; subclasses haven't had the chance to do their own initialization yet:

class X {
    constructor(setup: (obj: any) => void) { setup(this); }
}
class Y extends X {
    a: string[] = [];
}
var y = new Y(obj => {
    obj.a.push('foo'); // fails because obj.a is not set yet
});

@mhegazy
Copy link
Contributor

mhegazy commented May 24, 2016

Duplicate of #5863

@mhegazy mhegazy closed this as completed May 24, 2016
@mhegazy mhegazy added the Duplicate An existing issue was already created label May 24, 2016
@nin-jin
Copy link
Author

nin-jin commented May 25, 2016

@jeffreymorlan agree for this case :-) I am using this pattern now:

new X().setup( obj => {
    obj.foo = 2 // Ok, allowed
    // obj.bar = 3 // Ok, not allowed
} )

But it would be cool if we can use this:

new X().setup({
    foo : 2 , // Ok, allowed
    // foo : '3' , // Ok, not allowed
    // bar : 4 , // Ok, not allowed
})

But how to implement of strong intersection of type this and type of agrument?

@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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants