If all functions in JS are objects, and objects are just collections of key:value pairs - how do complex functions become objects? Say a function thats taking a param number, doing complex calculations on it and returning the result - how is that an object? How do you store it as key/value pairs?
Objects are collections of key-value pairs indeed, but they are not just so.
Think of this ability as an interface: given a JavaScript object, you are guaranteed to be able to access its members (or elements) via a syntax of obj.foo
or a obj['foo']
. But at the same time, they can also have other abilities. Functions, in this case, is an example that can be called by a fn()
syntax.
In fact, TypeScript allows you to declare a type that can do more than just key-value pairs:
type Type = {
'foo': RegExp; // a directly guaranteed member
[number]: string; // a rule-based convention:
// you can always get a string by a numeric index
// (or undefined)
Method(): number; // member function
get children: HTMLElement[]; // getter/setter
{ new(): SomeClass }; // constructor of certain type
};