So I'm reading this documentation and am really confused how this is even possible in JavaScript.
type DescribableFunction = {
description: string;
(a: any): boolean;
};
function doSomething(fn: DescribableFunction) {
console.log(fn.description " returned " fn(6));
};
doSomething((()=>false)); // Argument of type '() => false' is not assignable to parameter of type 'DescribableFunction'. Property 'description' is missing in type '() => false' but required in type 'DescribableFunction'.
doSomething({description: 'test'}); // fn is not a function.
As you can see above, how can the param fn
be both object and function at the same time..?
CodePudding user response:
Functions are a special type of object - they're essentially callable objects.
const fn = () => {};
console.log(fn instanceof Object);
The prototype chain for a function is:
fn <- Function.prototype <- Object.prototype
And objects can have arbitrary key-value pairs put on them.
'use strict';
const fn = () => {};
fn.prop = 'val';
console.log('prop is:', fn.prop);
So, for an example of how the function in your question could work, you could do:
const fn = Object.assign(
() => false,
{ description: 'test' }
);
doSomething(fn);
Now fn
is both callable and has a description
property which is a string.