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

Error: Initializer of instance member variable 'x' cannot reference identifier 'y' declared in the constructor. #2548

Closed
mpawelski opened this issue Mar 30, 2015 · 2 comments
Labels
By Design

Comments

@mpawelski
Copy link

@mpawelski mpawelski commented Mar 30, 2015

I got this error:

Initializer of instance member variable 'objectWithFunc' cannot reference identifier 'param' declared in the constructor.

for this piece of code:

interface ITest {
    foo: string;
    bar: string;
}

var param: ITest = null;

class Test {    

    constructor(param: ITest) {        
    }

    method() {        
        console.log(param.foo);
    }

    private objectWithFunc = {
        func: () => {
            console.log(param.foo);            
        }
    }
}

When I change parameter name in constructor to other name (for example constructor(param2: ITest)) it compiles.

This behaviour was surprising for me. Is it a bug?

@mpawelski
Copy link
Author

@mpawelski mpawelski commented Mar 30, 2015

I'm using Typescript 1.4 with Visual Studio Community 2013.

@mhegazy
Copy link
Contributor

@mhegazy mhegazy commented Mar 30, 2015

This is by design. Property initialization happens as part of constructying the object. the compiler will generate it as part of the constructor, that means that your constructor parameter "param" will shadow the variable "param" at runtime. this error message is letting you know that this is going to happen.

so the following ts code:

var param = null;
class Test {    
    constructor(param) {        
       //constructor body 
    }
    private property = param; // initialization
}

will be transformed to:

var param = null;
var Test = (function () {
    function Test(param) {
        this.property = param; // initialization
        //constructor body 
    }
    return Test;
})();

@mhegazy mhegazy added the By Design label Mar 30, 2015
@microsoft microsoft locked and limited conversation to collaborators Jun 18, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
By Design
Projects
None yet
Development

No branches or pull requests

3 participants