如何描述可调用的属性在打印稿?如何调用下面的函数?


type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
console.log(fn.description + " returned " + fn(6));
}
console.log(doSomething({description="how are you", (9)=>return true;})) //error

我试图调用上面的函数与一些参数,但我得到错误如下

"此表达式不可调用。类型'{描述:字符串;}'没有呼叫签名。(2349)(属性)描述:any">

如何调用这个函数?

您需要给您的函数字段一个名称,以便以后可以引用它。此外,在传递对象作为参数时还会出现一些语法错误:

type DescribableFunction = {
description: string;
call: (someArg: number) => boolean;
};
function doSomething(fn: DescribableFunction) {
console.log(fn.description + " returned " + fn.call(6));
}
console.log(doSomething({description: "how are you", call: (x: number) => true }))

游乐场

没问题!您可以使用Object.assign将属性附加到任何对象,包括函数。

你的代码的开头已经有效了,如果你像这样写,结尾也可以工作:

let described = Object.assign((x: number) => true, { description: "how are you" });
console.log(doSomething(described));

如果你感兴趣的话,下面是如何编写一个只附加一个属性的辅助函数:

/** Adds a property to any object, and returns the same object with a type that includes 
the new property. */
export function attachProp<T extends {}, PName extends string, PType>(
obj: T, prop: PName, value: PType
) {
(obj as any)[prop] = value;
return obj as T & { [p in PName]: PType };
}

用法:

let described = attachProp((x: number) => true, 'description', "how are you");
console.log(doSomething(described));

最新更新