简体   繁体   中英

TypeScript - How to define Function Type having arguments with any Type

I'm new to 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*/ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM