首页 > 解决方案 > 如何在打字稿中键入非空数组?

问题描述

如果未预先检查数组是否为空,我希望打字稿编译器在尝试直接访问数组的任何元素时抛出“对象可能是“未定义”错误,因此您始终必须检查该元素是否未定义,例如,使用可选链

如果预先检查了数组不为空,那么您需要能够像往常一样访问其元素,而无需检查其元素是否未定义

我需要这个以确保数组不为空,因此如果它为空,则对其任何元素的访问将立即返回 undefined 然后链接将不会继续,并且不会出现无法读取 undefined 属性等可能的错误

我该怎么做呢?

代码示例,也许它会让我的问题更清楚

interface Element {
  a: {
    aa: string;
    bb: string;
  };
  b: {
    aa: string;
    bb: string;
  };
}

const element: Element = {
  a: { aa: "aa", bb: "bb" },
  b: { aa: "aa", bb: "bb" },
};

type ElementArray = Element[];

const array: ElementArray = [element, element];
const emptyArray: ElementArray = [];

const getFirstAWithoutLengthCheck = (array: ElementArray) => {
  return array[0].a; // i want the typescript compiler to throw an 'Object is possibly 'undefined'' error here
};

const getFirstAWithLengthCheck = (array: ElementArray) => {
  if (array.length) {
    return array[0].a; // shouldn't be any errors
  }
  return null;
};

const getFirstAOptChaining = (array: ElementArray) => {
  return array[0]?.a; // shouldn't be any errors
};

// will throw error cannot read property a of undefined, so we need to use
// optional chaining or length check in this function, but typesript is not requiring it
console.log(getFirstAWithoutLengthCheck(array)); // aa
console.log(getFirstAWithoutLengthCheck(emptyArray)); // crash!

// checking array length, access to first element should work as usual, no errors
console.log(getFirstAWithLengthCheck(array)); // aa
console.log(getFirstAWithLengthCheck(emptyArray)); // null

// optional chaining, no errors
console.log(getFirstAOptChaining(array)); // aa
console.log(getFirstAOptChaining(emptyArray)); // undefined

标签: javascripttypescripttypescastingtype-conversion

解决方案


正如@Roberto Zvjerković 评论的那样,您需要使用noUncheckedIndexedAccess编译器标志。

游乐场(链接已noUncheckedIndexedAccess打开标志)。

但是,您需要使用而不是if (array.length),您需要这样做if (array[0])。这是因为,即使长度不为零,也不能确保元素是“未定义的”。如果数组是array = [undefined],它应该给出运行时错误。它与数组的类型无关,它是否可以包含undefined


推荐阅读