gpt4 book ai didi

typescript - TypeScript 接口(interface)是否具有匿名函数和命名函数?

转载 作者:搜寻专家 更新时间:2023-10-30 21:10:43 24 4
gpt4 key购买 nike

我认为接口(interface)很少同时具有匿名函数和命名函数。这是正确的吗?

TypeScript 编译器允许接口(interface)同时具有匿名函数和命名函数。

// no error
interface Foo {
(x: number, y: number): number; // anonymous
namedMethod: (z: string, w: string) => string; // named
}

但是好像不可用。

// badProp is not assignable
const foo1 : Foo = {
badProp(x: number, y: number) { return 1 },
namedMethod(a: string, b: string) { return 'str'; }
}

// syntax error
const foo2 : Foo = {
(x: number, y: number) { return 1 },
namedMethod(a: string, b: string) { return 'str'; }
}

使用任何类型,都可以。

const temp: any = function (x: number, y: number) { return 1 };
temp.namedMethod = function (a: string, b: string) { return 'str'; }
const foo3: Foo = temp;

虽然在技术上可以同时使用两者,但接口(interface)很少同时具有匿名函数和命名函数。这样对吗?

最佳答案

TypeScript 接口(interface)中的“未命名” 成员不是指匿名成员,而是声明接口(interface)类本身的函数签名,as described in this section of the documentation .

例如:

/**
* Interface for function that takes two numbers as arguments, and returns
* a number.
**/
interface TwoNumberFunction {
(x: number, y: number): number,
}

// simple function: adds two numbers
function add(x: number, y: number): number {
return x + y;
}

// 'add' is a function that takes two numbers and returns a
// number, so it matches the interface's requirements:
const func: NumberFunction = add;
func(1, 2); // = 3

关于typescript - TypeScript 接口(interface)是否具有匿名函数和命名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41082804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com