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?
warnUserdoes not match its declared type. TypeScript reports the mismatch in both cases.Property 'wasCalled' is missing in type '(warning: string) => void' but required in type 'WarnUser'.(2741) input.ts(3, 3): 'wasCalled' is declared here.