Reputation: 3375
I am reading ts handbook and I found something really confusing I am not sure how to use it. Basically is a param that is a function and a property at the same time.
// the definition
type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
// the function that acceps the params
function doSomething(fn: DescribableFunction) {
console.log(fn.description + " returned " + fn(6));
}
// but how can I use it?
// case 1 fail
doSomething({ description: 'xxx'})
/* Argument of type '{ description: string; }' is not assignable to parameter of type 'DescribableFunction'.
Type '{ description: string; }' provides no match for the signature '(someArg: number): boolean'.(2345)
*/
//case 2 fail
doSomething((x) => x > 0})
/*
Argument of type '(x: number) => boolean' is not assignable to parameter of type 'DescribableFunction'.
Property 'description' is missing in type '(x: number) => boolean' but required in type 'DescribableFunction'.(2345)
input.tsx(2, 3): 'description' is declared here.
*/
document https://www.typescriptlang.org/docs/handbook/2/functions.html#call-signatures
Upvotes: 2
Views: 112
Reputation: 1
the main point is : 1.first to declare Your function ,like: const fn: DescribableFunction = (someArg: number) => true
2.then to add value for property "description",like: fn.description = 'hello'; If You do 2. before 1.,wouldn't work.
Upvotes: 0
Reputation: 33051
This code
type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
means that there is some function (someArg: number): boolean
with static property description
.
Just like any function has static property name
or static methods call
,apply
,bind
...
type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
console.log(fn.description + " returned " + fn(6));
}
const fn: DescribableFunction = (someArg: number) => true
fn.description = 'hello';
doSomething(fn) // ok
Upvotes: 1