[英]TypeScript - How to define Function Type having arguments with any Type
I'm new to TypeScript. 我是TypeScript的新手。
I want to define Function Type having arguments with any Type. 我想定义具有任何类型参数的函数类型。 The function may one argument or more than two argument. 该函数可以是一个参数,也可以是两个以上参数。
How should I write? 我应该怎么写?
(args: any) => any
Writing this way above works only when one argument is passed to the function. 仅当将一个参数传递给函数时,以上编写这种方式才有效。
class NotificationCenter {
private observerList: Array<() => any>;
constructor() {
this.observerList = [];
}
addObserver(observer: () => any): void {
this.observerList.push(observer);
}
}
let notificationCenter: NotificationCenter = new NotificationCenter();
let observer1 = () => {};
let observer2 = (text: string) => {return "observer2"};
let observer3 = (id: number, data: Array<any>) => {return "observer3"};
//This works fine.
notificationCenter.addObserver(observer1);
//Error:Argument of type '(text: string) => string' is not assignable to parameter of type '() => any'.
notificationCenter.addObserver(observer2);
//Error:Argument of type '(id: number, data: any[]) => string' is not assignable to parameter of type '() => any'.
notificationCenter.addObserver(observer3);
You say the function can have one argument or more than two arguments. 您说函数可以有一个参数或两个以上参数。 That sounds like it can have one or 3 or more arguments. 听起来可以有一个或三个或多个参数。 You'll have to overload it then. 然后,您将不得不重载它。
function foo(arg: any): any { /*do work*/ }
function foo(arg: any, arg2: any, ...rest: any[]): any { /*do work*/ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.