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

118
Visualizações
Initializing object when strictNullChecks used in Typescript

I have an interface called IUser and uses strictNullChecks in the typescript setting. I want to use a variable of IUser in the class like below:

class UserAccount {
    user: IUser;
}

The above code will generate the error:

Property 'user' has no initializer and is not definitely assigned in the constructor.

I can fix this with:

class UserAccount {
    user: IUser;
    constructor() {
        user = new User();
    }
}

But from a run time perspective, the user can be set only after a while after the display is complete. There is a latency for getting the data for the user from the server. The setting of the user is done through an RxJS observable which works only reactively.

What type of initialization I can do for user so that it can be set only later time. Setting user to null or undefined may not be correct because I use strictNullChecks and showing the intention that the object will be present from the beginning. But a valid object for user can't exist until the server call is complete.

*** UPDATE ****

This is a little more better example than the above:

export class AddPersonDialogComponent {

  selectedPerson1: IPersonForTypeahead;
  selectedPerson2: IPersonForTypeahead;
  selectedPerson3: IPersonForTypeahead;

  ...
}

The 3 selectedPerson objects are assigned values when the user select them from three 3 dropdowns in the dialog. These three properties start with nothing but if the user select people from a drop down in the dialog, they are set.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could make your usage of UserAccount to be an observable, like this:

userAccount$: Observable<UserAccount> = this.service.getUser().pipe(
    map(user => new UserAccount(user))
);

The idea here is to not construct your UserAccount until you have all the data needed to do so. This goes along with your idea "But a valid object for user can't exist until the server call is complete" .

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