我知道如何在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
}所以问题是:上面的类型定义到底是什么意思?是否可以创建与此签名匹配的对象?
发布于 2020-02-11 20:52:03
这是另一种编写方式:
type Foo = (a: string) => number;...but您还可以包含函数的其他属性,例如:
type Foo = {
(a: string): number;
b: boolean;
};...defines函数的类型,它接受一个字符串,返回一个数字,并且(在函数上)有一个布尔值的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; // <== Workshttps://stackoverflow.com/questions/60169126
复制相似问题