4

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);
3
  • 5
    I think what you want is (...params : any[]) => any. See this Commented Mar 31, 2016 at 15:00
  • Thanks! That's what I need! Commented Apr 1, 2016 at 22:21
  • @tforgione I think this is a good answer. If you submit it as an answer I'll upvote it. Commented Mar 7, 2023 at 23:40

1 Answer 1

1

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*/ }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.