I am using Typescript with vue. The problem is that I have declared an instance property named categoryList
which will be populated when the component renders on the runtime with an array from an api call. So, when I am referencing this property in another method like this:
this.categoryList.length && this.categoryList[0]
since I know that this will have some value when the method executes
TS gives me a warning.
Since categoryList will be an array of Object, if I access it like this
this.categoryList[0].source_id
I get the following warning
Instead, if I access it like this this.categoryList[0]
I get the following warning
But, how can I avoid this kind of warning for such cases where value will be assigned on run time in the future to an instance property being refernced.
class Alerts extends Vue {
private activeView: number = VIEW.NEW;
private categoryList: [] = [];
mounted() {
this.fetchCategories()
}
/*
* method to fetch from an api call
*/
fetchCategories() {
this.$axios.get(CATEGORY_URL).then((res) => {
categoryList = res.data
})
}
doSomethingWithCategories() {
// have to use categoryList here
const use = this.categoryList.length && this.categoryList[0] // This warns me that Object is possibly undefined
// ...
}
}
As advised by @Mark, I am already using conditionals to ensure value availability but still getting warning.