我知道如何在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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句