【发布时间】:2023-03-07 22:09:02
【问题描述】:
我想检查一个对象内的数组是否存在,不为空也不为空
我需要在括号中引用该属性。
我的对象
profile = {
myArray: [1,2,3]
}
我正在像这样检查它
const section = "myArray";
if(section in profile && profile[section] && profile[section].length ) { // do something}
我希望这能正常工作,但我在这部分 profile[section].length 中收到一个错误,上面写着 object is possibly null or undefined
如果我使用点表示法,它可以正常工作
if('myArray' in profile && profile.myArray && profile.myArray.length ) { // do something}
【问题讨论】:
-
错字?
myArray = [1,2,3]= 应该是冒号。 -
@evayly 是的,这是一个错字,谢谢
-
在 TypeScript 中,无论何时使用
object[...]表示法,它都依赖于object的索引签名。因此,它无法判断您已检查真实性的属性与您正在访问的length属性相同的属性。
标签: typescript object null