Force JavaScript exception/error when reading an undefined object property?

后端 未结 7 1207
后悔当初
后悔当初 2020-11-30 04:29

I\'m an experienced C++/Java programmer working in Javascript for the first time. I\'m using Chrome as the browser.

I\'ve created several Javascript classes with fie

7条回答
  •  余生分开走
    2020-11-30 05:04

    As of now, the "right" solution to this is to use TypeScript (or another type-checking library such as Flow). Example:

    const a = [1,2,3];
    
    if (a.len !== 3) console.log("a's length is not 3!");
    

    On JavaScript, this code will print "a's length is not 3!". The reason is that there is no such property len on arrays (remember that you get the length of an array with a.length, not a.len). Hence, a.len will return undefined and hence, the statement will essentially be equal to:

    if (undefined !== 3) console.log("a's length is not 3!");
    

    Since undefined is indeed not equal to 3, the body of the if statement will be run.

    However, on TypeScript, you will get the error Property 'len' does not exist on type 'number[]' right on the "compile time" (on your editor, before you even run the code).

    Reference

提交回复
热议问题