Typescript接口函数成员
我是打字新手。我无法理解界面的以下用法: 比如说,有一个函数:Typescript接口函数成员,typescript,Typescript,我是打字新手。我无法理解界面的以下用法: 比如说,有一个函数: function test(arg1: ITest):number { return 20; } 如果ITest界面如下所示: interface ITest { (props: string):number; a1?: number; } interface ITest { (props: string):number; a1: number; //Removed the o
function test(arg1: ITest):number {
return 20;
}
如果ITest
界面如下所示:
interface ITest {
(props: string):number;
a1?: number;
}
interface ITest {
(props: string):number;
a1: number; //Removed the optional sign "?"
}
然后,以下调用有效:
const obj = {
func: (p: string): number => (10+2),
};
test(obj.func); //Should not I pass obj instead of obj.func ?
问:我是否应该通过obj
而不是obj.func
但是,如果接口如下所示:
interface ITest {
(props: string):number;
a1?: number;
}
interface ITest {
(props: string):number;
a1: number; //Removed the optional sign "?"
}
Q:那么我应该向测试函数传递什么参数
问:上面的接口和下面更改的接口声明有什么区别
interface ITest {
func: (props: string)=>number; //changed it from (props: string):number;
a1: number;
}
谢谢你解答我的疑问。我将从JS/TS中的函数开始。函数是一个对象,这意味着与任何其他对象一样,函数也可以有方法和属性。这甚至可以在基本函数对象中看到,因为它有
apply
或bind
等方法。在任何给定时刻,您都可以将属性附加到任何函数。考虑
const f = (a:string) => a
f.prop = 1;
// take a type from f
type F = typeof f;
它是完全有效的TS代码。如果我们询问上述函数的类型,它将是:
type F = {
(a: string): string;
prop: number;
}
如您所见,上面的代码与示例代码非常接近。实际上,我们这里有TS中的函数对象,它有函数的主要定义,形式是(a:string):string
和其他属性,如prop
或示例中的a1
这个定义和标准的对象类型定义非常相似,这并不是一个错误,正如我们所说的函数只是一个对象
如果函数没有其他属性,则可以通过两种方式定义类型:
type F1 = {
(props: string):number;
}
type F2 = (props: string) => number
上面的F1
和F2
定义是相等的,但第一个定义提供了向函数对象附加附加属性的机会,而第二个定义不允许这样做
我们如何用属性创建函数的有效对象,请考虑下面的代码片段:
interface F1 {
(props: string):number;
a1: number;
}
// below preparation of object by temporary f1
const f1 = (props: string) => 1
f1.a1 = 2;
const a: F1 = f1; // a is valid value type F1
在您的示例中,a1
是可选的,因此不需要提供,说明这样的定义是有效的:
const f1: F1 = (props: string) => 1
好的,最后一件事是带有func
属性的对象,它实际上是另一件事
const obj = {
func: (p: string): number => (10+2),
};
type Obj = typeof obj;
如果我们检查什么是Obj
类型,它是:
type Obj = {
func: (p: string) => number;
}
所以它是不同的类型,它说我们没有函数对象,而是一个方法为func
的对象。我们可以很容易地比较这两种类型
type FunctionType = {
(props: string):number;
}
const f: FunctionType = props => 1
type ObjectWithMethodType = {
func: (props: string) => number
}
const obj: ObjectWithMethodType = {
func: props => 1
}
我希望这个解释有帮助
问:我是否应该通过obj而不是obj.func
ITest
是一个。它描述函数本身,而不是具有函数属性或方法的对象
Q:那么我应该向测试函数传递什么参数
现在,您已经将ITest
声明为具有必需属性a1
的函数类型。函数上的通过使用函数声明或const
表达式在TS中工作:
问:上面的接口和下面更改的接口声明有什么区别
ITest
现在已成为具有func
和a1
属性的对象的接口声明
const o1: ITest = {
func: s => 137,
a1: 42
}