Search code examples
typescriptreact-typescript

How to make a typescript function that can be called, but can't be treated as value?


I've recently had a bug like this in my codebase:

const isMounted = useIsMounted();

//... later

if (isMounted) {
  // Some action
}

Except, oops! isMounted is a function with signature () => boolean, not a boolean. It should have been "isMounted()". A subtle bug.

Can you think of a way to prevent this kind of bug using typescript somehow?

Eg. declare that function is never for the purposes of querying its value, and yet still be able to call it?


Solution

  • Turn on the strictNullChecks tsconfig option, and it will produce an error as expected:

    enter image description here

    This condition will always return true since this function is always defined. Did you mean to call it instead?(2774)