Is it in TypeScript somehow possible to define a type so that it only includes objects but not functions?
Example:
type T = { [name: string]: any } // How to modify this to only accepts objects???
const t: T = () => {} // <- This should not work after modification
Thanks for your help.
There's no perfect way to refer to a type like "an object which is not a function", since that would require true subtraction types, and that doesn't exist in TypeScript (as of 3.1 at least).
One easy-enough workaround is to look at the
Function
interface and describe something which is definitely not aFunction
, but which would match most non-function objects you're likely to run into. Example:That means "an object with some unspecified keys, which is either missing a
bind
property or acall
property". Let's see how it behaves:Good.
The reason that this is a workaround and not a straightforward solution is that some non-functions might have both a
call
and abind
property, just by coincidence, and you'll get an undesirable error:If you really need to support such objects you can change
NotAFunction
to be more complicated and exclude fewer non-functions, but there will likely always be something the definition gets wrong. It's up to you how far you want to go.Hope that helps. Good luck!