如何使用括号表示法检查打字稿中的无效性

lui*_*ero 4 null object typescript

我想检查对象内的数组是否存在、不为空且不为空

我需要用括号表示法引用该属性。

我的对象

profile = {
    myArray: [1,2,3]
}
Run Code Online (Sandbox Code Playgroud)

我正在这样检查

const section = "myArray";
if(section in profile && profile[section] && profile[section].length ) { // do something}
Run Code Online (Sandbox Code Playgroud)

我希望这能起作用,但我在这部分收到一个错误profile[section].length,上面写着object is possibly null or undefined

如果我使用点符号来做到这一点,它就可以正常工作

if('myArray' in profile && profile.myArray && profile.myArray.length ) { // do something}
Run Code Online (Sandbox Code Playgroud)

Avo*_*ion 10

像这样使用可选链

if (profile?.[section]?.length) { // do something }
Run Code Online (Sandbox Code Playgroud)

请参阅/sf/answers/4114662821/