Typescript: can you use constructor properties within a class's private properties?

Is it bad practice to use a constructor properties of a class within a variable? I tried this and was surprised const name = new Name(time, course); worked, although I guess it makes sense since an instance of Eng needs those constructor properties to be made, then they’d be available to use elsewhere.

import { Name } from './Name'

class Eng {
   private _name = new Name(time, course);

   private constructor(time: String, course: String) {} 

   method1(){
      let results = name.convertTrials();

      return results;
   }
}

>Solution :

Your code example actually has type errors:

class Eng {
   private _name = new Name(time, course);
   // Cannot find name 'time'.(2304)
   // Cannot find name 'course'.(2304)

   private constructor(time: string, course: string) {} 
}

time and course are not in scope as far as typescript is concerned. If you want to use constructor parameters, they must be in constructor body.


What may be confusing you is that, when compiled, the code runs fine. That is because non-static class properties are moved into the constructor for you, since that is where they would need to be in plain JS.

So your compiled class looks like:

// js
class Eng {
    constructor(time, course) {
        this._name = new Name(time, course);
    }
}

Which should work without a problem.

But it is a problem for Typescript, which believes that the constructor arguments are not in scope outside of the constructor.


If you don’t need the arguments:

class Foo {
    constructor() {}
}

class UseFoo {
   private foo = new Foo()
   private constructor() {} 
}

Then there isn’t anything wrong with your approach.

See Playground

Leave a Reply