Property has no initializer and is not definitely assigned

by Stephen Fluin

2018-06-26

Property has no initializer and is not definitely assigned
If you have ever seen an error that looks like Property 'X' has no initializer and is not definitely assigned in the constructor., then you probably just updated your TypeScript version or strictness flags. Here's how to fix it.
One of the new flags that landed as part of TypeScript 2.7 was the --strictPropertyInitialization flag. This flag is also implied by --strict so many developers may be seeing this error for the first time.
Before
class C {
    name: string
}

If you are seeing this error, you have two main options for resolving it the right way.

Option 1 - Initialize the property

Give the property a value to ensure that it is initialized.
After
class Person {
    name = '';
}

You can also do this in the constructor like this:
class Person {
    name: string;
    constructor() {
        this.name = '';
    }
}

Option 2 - Make the property optional

If some instances of your class won't have this property defined, you can let the type system know by making the property optional.
class Person {
    name?: string;
}

By making one of these two changes, your codebase should be ready for TypeScript 2.7 and above, even in strict mode.
There's a third way, but you shouldn't do this. You can just override the warning by added an ! instead of a ?.

Doing this in an Angular app?

This can be trickier for Angular apps using decorators like @ViewChild or @ContentChildren, your best bet is to make the property optional.
If you are defining an Observablein your ngOnInit, look at moving it to your constructor. In general the best practice is to define your streams in your constructor, and then subscribe to them from your template.
If you are using an @Input() decorator, you should provide a default value, or mark the property as optional.
The best practice for using @Output() is to immediately define the new EventEmitter<type>().