TypeScript compiler evaluates let differently than const

前端 未结 1 1647
一生所求
一生所求 2021-01-05 15:10

Following page 64 in Boris Cherny\'s Programming TypeScript, consider a JavaScript function like this:

function warnUser(warning) {
  if (warnUser.w         


        
相关标签:
1条回答
  • 2021-01-05 15:39

    Function property assignments are only allowed on function declarations and const variables initialized with a function/arrow expression. This is a rule ingrained in the compiler, as described in the TS 3.1 changelog.

    Why is let problematic but const fine?

    Probably because of safety reasons. let creates a mutable binding, so you potentially could have reassigned another value before and aren't setting a property on the function expression anymore.

    TS also forbids double function declarations, therefore both rules can be statically analyzed and enforced in a predictable way.

    0 讨论(0)
提交回复
热议问题