42

I am getting an error when I give

export class UserComponent implements OnInit {
    user: User;

    constructor() { }

    ngOnInit() {
        this.user = {
            firstName : "test",
            lastName : "test",
            age : 40,
            address: {
                street : "Test",
                city : "test",
                state: "test"
            }
        }
    }
}

I am getting this error (see image 1):

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

user is instantiated from User which is declared in User.ts by this code:

export interface User {
    firstName: string,
    lastName: string,
    age?: number,
    address?: {
        street?: string,
        city?: string,
        state?: string
    }
}

If I add a question mark (?) to user, another error appears in some other file (see image 2):

Error occurs in the template of component UserComponent.
src/app/components/users/users.component.html:2:44 -
    error TS2532: Object is possibly 'undefined'.

2 <ul class="list-unstyled" *ngIf="loaded && users?.length > 0">
                                             ~~~~~~~~~~~~~~~~~
8
  • Well it isn't initialised or assigned in the constructor, is it? You could avoid that error by doing that, rather than in ngOnInit.
    – jonrsharpe
    Commented Nov 17, 2020 at 11:19
  • 1
    Yeah..But in the course, they said that Constructor is used for injecting dependencies..I still get the second error (in pic 2 in the question) after adding them in the constructor
    – user14653534
    Commented Nov 17, 2020 at 11:22
  • 2
    I don't know what course you're doing, but it doesn't have to be exclusively for that. I had to switch from ngOnInit to constructor when turning on strict mode, but all the tests still passed. And it's unclear what you expected in the last two screenshots - 1. making it optional in one place doesn't make it optional everywhere; and 2. if it's optional users?.length is potentially undefined.
    – jonrsharpe
    Commented Nov 17, 2020 at 11:39
  • Ohk...Why is users?.length undefined? I don't want to mention the course name here..It might be against the rules of stack overflow
    – user14653534
    Commented Nov 17, 2020 at 12:15
  • It's potentially undefined, because if users is optional then users can be undefined, in which case users?.length is also undefined. Why would mentioning the resources you're getting information from be a problem?
    – jonrsharpe
    Commented Nov 17, 2020 at 12:16

6 Answers 6

139

This is caused by TypeScript's Strict Class Initialization.

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#strict-class-initialization

To resolve this issue you must either declare that the type can be both Foo|undefined, or utilize the '!' symbol to indicate definite assignment as per the above documentation:

Case 1:

@Component({...})
export class Component {
  @Input() myInput: string|undefined;
}

We indicate that the type may be either a string or undefined.

Case 2:

@Component({...})
export class Component {
  @Input() myInput!: string;
}

In this case we utilize the ! symbol to indicate that we are aware that myInput is not initialized in the constructor and we will handle it elsewhere.

Alternate Solution

If you do not care about strict class initialization, you can disable the feature completely in your tsconfig.json by adding a flag to your compiler options

{
 "compilerOptions": {
    "strictPropertyInitialization": false
  }
}

Note: You will have to restart the TypeScript server for the compilerOptions to be reapplied. The easiest way to achieve this is to simply restart your IDE.

3
  • Even if I used myInput!: string; when I write myInput = undefined I get an error saying undefined is not assignable to type
    – canbax
    Commented Sep 27, 2021 at 7:51
  • 3
    Right, when you utilize the ! that is like a promise you make that this value will NOT be undefined, which is why the compiler considers it a mistake to assign it undefined. The correct usage would be to simply write myInput!: string and ensure it holds a string value before its first usage, even if that is an empty string, such as myInput = "" Commented Sep 27, 2021 at 8:55
  • MAN!! I've been stuck on this issue for 30 minutes, Thanks!
    – Alaa Jabre
    Commented Dec 22, 2021 at 14:28
5

If none of this works, you can try it

  "angularCompilerOptions": {
    ....
    "strictPropertyInitialization": false,
    ...

  }
2

I think your course was correct. BUT, I think it is mostly fine to move things from ngOnInit if they are not related to rendering.

IMO, Angular makes a quick rule to avoid some rendering issue but it is not a black and white one. The rule I think it is just trying to make thing simple for new users. And this is a more advance topic.

quote from https://github.com/angular/angular/issues/24571#issuecomment-404606595

For angular components, use the following rules in deciding between:
a) adding initializer
b) make the field optional
c) leave the '!'

If the field is annotated with @input - Make the field optional b) or add an initializer a).
If the input is required for the component user - add an assertion in ngOnInit and apply c.
If the field is annotated @ViewChild, @ContentChild - Make the field optional b).
If the field is annotated with @ViewChildren or @ContentChildren - Add back '!' - c).
Fields that have an initializer, but it lives in ngOnInit. - Move the initializer to the constructor.
Fields that have an initializer, but it lives in ngOnInit and cannot be moved because it depends on other @input fields - Add back '!' - c).

I think this is a good guideline

1

This can be resolve the issue by using the add type to undefined with or-operator or else use "!" symbol in the character like below:

igame!: IGame;

igame: IGame | undefined;

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Mar 26, 2022 at 23:06
1

"strictPropertyInitialization": false, put this at you tsconfig.json in compileroption

1

Please use like this.

user!: User

Tip: Please use ! after the variable uninitialized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.