Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

347
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda