typescript - 打字稿类型中的匿名函数签名。这是什么意思?
问题描述
我知道如何在 TypeScript 中定义一个需要这样的命名函数的类型:
type Foo = {
bar(a: string): number
}
// or
type Foo = {
bar: (a:string) => number
}
然而,使用第一种方法,也可以定义一个没有名字的函数,如下所示:
type Foo = {
(a: string): number
}
TypeScript 编译器在这里没有抱怨,但我不知道如何创建与此类型签名匹配的对象?尝试这样的事情不会编译:
let f: Foo = {
(a: string) => 2
}
所以问题是:上面的类型定义实际上是什么意思?是否可以创建与此签名匹配的对象?
解决方案
这是另一种写法:
type Foo = (a: string) => number;
...但您也可以包含该函数将具有的其他属性,例如:
type Foo = {
(a: string): number;
b: boolean;
};
...为接受字符串、返回数字并具有b
布尔属性(在函数上)的函数定义类型。
// Your type
type Foo = {
(a: string): number;
};
// Equivalent type
type Bar = (a: string) => number;
// Proving they're equivalent (or at least compatible)
const a: Foo = (a: string) => 42;
const b: Bar = a; // <== Works
// Including a property on the function
type Foo2 = {
(a: string): number;
b: boolean;
};
// Creating one
const x1 = (a: string): number => 42;
let f1: Foo2 = x1; // <== Error because `x1` doesn't have `b`
const x2 = (a: string): number => 42;
x2.b = true;
let f2: Foo2 = x2; // <== Works
推荐阅读
- elasticsearch - 无法在 Elasticsearch 批量索引上指定“路由”字段 (routing_missing_exception)
- python - Wolfram API“数据不可用”消息
- c++ - 添加三个 std::vectors 并将结果存储在第一个向量中
- apache-spark - 在 Pyspark 中创建新列时出错
- python - 当我不希望它重复时,功能正在重复
- html - 有没有办法编辑 fontawesome 图标的边缘或边框?
- python - 如何在不读取其余行的情况下搜索满足一组条件的第一行的 pandas DataFrame?
- javascript - 事件侦听器在循环函数之外调用时不起作用,但在其中声明时被一遍又一遍地声明?
- android - Android 应用程序在尝试从设备源获取图像时隐藏
- amazon-web-services - Kubectl with Gitlab EKS Cluster Error: You must be logged in to the server (Unauthorized)