当数组也可以为空时,在 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) 当使用对象数组时,是否可以在循环中将v-for当前对象分配给变量并同时破坏其属性?像这样的东西:
<div v-for="(person = {name, age}, index) in persons">
Run Code Online (Sandbox Code Playgroud)
person最终,我正在寻找一种在模板中使用整个对象及其属性的方法。