[Vuejs]-How to avoid 'Object is possibly null' warning on properties that will be populated in the future

1๐Ÿ‘

โœ…

Here is your issue:

 private categoryList: [] = [];

Should be:

 private categoryList: YourDataType[] = [];

When you define an array as type [] you are essentially telling Typescript that the value of this variable will only ever be a tuple of size 0, or [].

-1๐Ÿ‘

An interesting thing to note: If you know for sure that categoryList will have a value when code executes, then you can get away with the warning with following hack. But its not advisable to use it often as we should apply null/undefined checks wherever required.

this.categoryList![0].source_id

! tells typescript that the object preceding it will always have a value when the code runs.

For more info, please check this answer.

Leave a comment