小编And*_*man的帖子

在 Typescript 中按索引访问时如何处理潜在的空数组

当数组也可以为空时,在 Typescript 中通过索引访问数组中的元素的首选方法是什么undefined

我正在使用 Typescript 在 React 中编写一个简单的游戏,其中有一个由gametype 集合数组组成的变量ISet。在这个简化的示例中,它的接口中ISet有一个score属性,我尝试访问该属性

const game: ISet[] = [];
const currentSet = game[game.length - 1]; // 'currentSet' will be of type 'ISet', although it will be 'undefined' here
console.log(currentSet.score); // No Typescript error, although a 'Uncaught TypeError: Cannot read property 'score' of undefined' error will be thrown when run
Run Code Online (Sandbox Code Playgroud)

我怎样才能让 Typescript 检测到这里currentSet可能存在undefined

我尝试手动将 的currentSet类型设置为

const currentSet: ISet | undefined …
Run Code Online (Sandbox Code Playgroud)

types typescript

6
推荐指数
2
解决办法
5451
查看次数

v-for:数组元素和属性解构

当使用对象数组时,是否可以在循环中将v-for当前对象分配给变量并同时破坏其属性?像这样的东西:

<div v-for="(person = {name, age}, index) in persons"> 
Run Code Online (Sandbox Code Playgroud)

person最终,我正在寻找一种在模板中使用整个对象及其属性的方法。

vue.js vue-component vuejs2

6
推荐指数
1
解决办法
4801
查看次数

标签 统计

types ×1

typescript ×1

vue-component ×1

vue.js ×1

vuejs2 ×1