typescript - 如何在打字稿中定义函数调用签名的实现和构造签名
问题描述
打字稿文档讨论了函数call signatures
,construct signatures
并描述了如何声明类型和使用它。https://www.typescriptlang.org/docs/handbook/2/functions.html#call-signatures
调用签名(没有实现 type 的函数DescribableFunction
)
type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
console.log(fn.description + " returned " + fn(6));
}
构造签名(没有实现 type 的函数SomeConstructor
)
type SomeConstructor = {
new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
return new ctor("hello");
}
但它从未显示如何定义这些函数的实际实现。我搜索了很多天,但似乎找不到任何东西。一个简单的例子,说明如何使用它以及何时使用它,对于理解这些概念非常有帮助。
我试图这样做,call signatures
但显然它的抛出错误
type DescribableFunction = {
description: string;
(str: string): string;
}
const df: DescribableFunction = {
description: 'df function description',
(str: string): {
return str;
}
}
console.log(df.description, df('hello world'));
解决方案
没有用于声明具有额外属性的函数的“文字”语法。
但是函数是普通对象,可以给它们添加属性:
const df: DescribableFunction = (str: string) => {
return str;
}
df.description = "df function description"
通常,Typescript 会抱怨description
在 的初始声明中缺少属性df
,但看起来它对函数做了一个例外,允许稍后添加它们。
至于构造函数签名,它们很好地映射到类语法。举个例子:
type CacheableConstructor = {
new(s: string): { x: number };
cached: boolean
};
它可以这样实现:
class SomeCC {
static cached = false
x: number
constructor(s: string) {}
}
// check that if matches the constructor signaure
const cc: CacheableConstructor = SomeCC
推荐阅读
- excel - 使用 REGEX 进行字段验证
- python - 我怎么知道在 Pygame 中是否触摸了一个圆和一个矩形?
- ruby-on-rails - 在 Rails 中处理具有权限的团队
- react-native - http://localhost:8081/debugger-ui/ 不工作
- javascript - [HTML CSS JS]防止用户使用before元素改变值
- javascript - php中一个列表中的多个值
- vb.net - VB.net DownloadDataAsync 到 MemoryStream 不起作用
- angular - angular2导出到excel
- php - 注意:未定义索引:上传文件时的文件
- bash - 蜘蛛 wget 只返回目录但不返回文件