6

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

function warnUser(warning) {
  if (warnUser.wasCalled) {
    return
  }
  warnUser.wasCalled = true
  alert(warning)
}
warnUser.wasCalled = false

which will warn a user no more than once. We want to use TypeScript to type its full signature:

type WarnUser = {
  (warning: string): void
  wasCalled: boolean
}

Then we can implement it in TypeScript like so:

const warnUser: WarnUser = (warning) => {
  if (warnUser.wasCalled) {
    return
  }
  warnUser.wasCalled = true
  alert(warning)
}

but try the same thing with let instead of const and you get an error:

let warnUser: WarnUser = (warning) => {
  if (warnUser.wasCalled) {
    return
  }
  warnUser.wasCalled = true
  alert(warning)
}

Property 'wasCalled' is missing in type '(warning: string) => void' but required in type 'WarnUser'.ts(2741)>

Why is let problematic but const fine?

3
  • The value you use to initialize warnUser does not match its declared type. TypeScript reports the mismatch in both cases. Commented Jan 23, 2020 at 21:18
  • 1
    This is interesting. At first I assumed you made a typo, but can confirm this behaviour.Property 'wasCalled' is missing in type '(warning: string) => void' but required in type 'WarnUser'.(2741) input.ts(3, 3): 'wasCalled' is declared here. Commented Jan 23, 2020 at 21:27
  • And changing the let tot a const makes the problem go away Commented Jan 23, 2020 at 21:28

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.