Reputation: 67
I am reading the Typescript Handbook and, right now, I am currently stuck at Call Signatures subsection. In the example given:
type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
console.log(fn.description + " returned " + fn(6));
}
I cannot figure out in TS Playground how to invoke the doSomething
function. I tried the below but it is not working.
doSomething({ description: "The code", (5): false})
Upvotes: 6
Views: 731
Reputation: 184526
Functions with additional properties seem unergonomic; at least you cannot declare them using a single plain object.
This is one way:
const fn = ((x: number) => false) as DescribableFunction;
fn.description = 'description';
doSomething(fn);
Upvotes: 1
Reputation: 328272
A DescribableFunction
is first and foremost a function that takes a single number
input and returns a boolean
. It also has a string
-valued description
property.
Since TypeScript 3.1, and as implemented in microsoft/TypeScript#26368, you've been allowed to add properties to functions after their declarations without running into compiler warnings. So you can make a DescribableFunction
relatively straightfowardly.
Here's how you could do it with a function statement:
function greaterThanTen(someArg: number) {
return someArg > 10;
}
greaterThanTen.description = "greaterThanTen";
doSomething(greaterThanTen); // "greaterThanTen returned false"
And here's how you could do it with a function expression:
const isEven: DescribableFunction = someArg => someArg % 2 === 0;
isEven.description = "isEven"
doSomething(isEven); // "isEven returned true"
If you want a one-liner, you could use Object.assign()
to add properties to a target and return the augmented target, which TypeScript represents as the intersection of the function type and the added property objects. (This worked even before TypeScript 3.1.) Observe:
const isNegative = Object.assign(
(someArg: number) => someArg < 0,
{ description: "isNegative" }
);
doSomething(isNegative); // "isNegative returned false"
Upvotes: 6