0

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.

wonderful world
  • 10,969
  • 20
  • 97
  • 194
  • 3
    "*showing the intention that the object will be present from the beginning*" and "*the `user` can be set only after a while*" don't go together. Which one is it? – Bergi May 22 '22 at 16:20

1 Answers1

3

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" .

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
BizzyBob
  • 12,309
  • 4
  • 27
  • 51
  • I used `UserAccount` as an example. This class can be an angular component class. So, the parent class can't be converted to an `Observable`. The question is around the property `user` and what it can be initialized with when `strictNullChecks` is used. – wonderful world May 22 '22 at 21:05
  • 1
    Can you add an example to your question? Maybe [this question/answer](https://stackoverflow.com/questions/66603888/where-to-initialise-a-formgroup-in-reactive-forms) may be of some help for you. – BizzyBob May 22 '22 at 22:20
  • I added an example under **UPDATE** in the original post. – wonderful world May 22 '22 at 23:01