我在vue中使用Typescript。问题是我已经声明了一个名为categoryList
的实例属性,当组件在运行时使用api调用的数组呈现时,将填充该实例属性。因此,当我在这样的另一种方法中引用此属性时:
this.categoryList.length && this.categoryList[0]
,因为我知道该方法执行时将具有一定的价值
TS给我警告。
由于categoryList将是Object的数组,如果我这样访问它
this.categoryList[0].source_id
我收到以下警告
相反,如果我这样访问this.categoryList[0]
我收到以下警告
但是,在将来会在运行时将值分配给引用的实例属性的情况下,如何避免这种警告。
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
// ...
}
}
根据@Mark的建议,我已经在使用条件语句来确保值的可用性,但仍会收到警告。
答案 0 :(得分:1)
这是您的问题:
private categoryList: [] = [];
应该是:
private categoryList: YourDataType[] = [];
当您将数组定义为类型[]
时,您实际上是在告诉Typescript该变量的值只会是大小为0或[]
的元组。
答案 1 :(得分:-1)
一个有趣的事情要注意:如果您确定在代码执行时categoryList将具有一个值,那么您可以通过以下hack摆脱警告。但是不建议经常使用它,因为我们应该在需要的地方应用null / undefined检查。
this.categoryList![0].source_id
!告诉打字稿,代码运行时,位于它前面的对象将始终具有值。
有关更多信息,请检查this answer。