Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

345
Views
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;
   }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!