typescript - ts 一个同时是函数和属性的类型
问题描述
我正在阅读 ts 手册,我发现一些非常令人困惑的东西,我不知道如何使用它。基本上是一个参数,它同时是一个函数和一个属性。
// 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.
*/
文档 https://www.typescriptlang.org/docs/handbook/2/functions.html#call-signatures
解决方案
这段代码
type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
意味着有一些(someArg: number): boolean
具有静态属性的功能description
。
就像任何函数都具有静态属性name
或静态方法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
推荐阅读
- elasticsearch - Elasticsearch 7 unable to create index
- vb.net - 如何在 VB.Net 2017 Form 中设置动态创建的 TextBox 的大小
- java - 双重着墨列表的反向功能跟踪问题
- python - 使用什么方法来学习信号数据中的特定区域
- android - 我应该如何更改我的应用程序的推送通知图标
- javascript - 登录在登录状态下无法正常工作更新未重新渲染
- django - Django 如何在 transaction.atomic() 中保存日志
- git - 如何设置在 RStudio 中查看以前的提交消息
- laravel - 使用引导插入数据后如何触发事件?(拉拉维尔)
- javascript - 有没有办法使用 Javascript 从文件夹中读取所有 .jpg 文件名?