jhon.smith
jhon.smith

Reputation: 2043

How does this TypeScript function parameter work

I found this code online and trying to understand it.

public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]> {


    //Create a function that considers the specified $index parameter value
    let getCities = (text$: Observable<string>) => 
        text$
            .debounceTime(300)
            .distinctUntilChanged()
            .switchMap( query => {

                //some logic involving $index here
                //...

                //query.length < 2 ? [] : this.apiService.getCities(query).catch(() => {
                //return Observable.of([]);
            });

    //Return that "custom" function, which will in turn be called by the ngbTypescript component
    return getCities;
}

My question revolves around the method signature.

public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]>

I understand

$index: any is an input parameter of type Any.

The function returns Observable an observable of any.

But what is : (text: Observable<string>)

Is it a second parameter?

If its a second parameter shouldn't it be

public searchFunctionFactory($index: any ,text: Observable<string>) => Observable<any[]> 

Upvotes: 1

Views: 51

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371233

That indicates that the return value of the searchFunctionFactory function is a function which takes a parameter of text, whose type is Observable<string>, and calling that function returns an Observable<any[]>. It's a higher-order function.

public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]> {
                        /*   ^^^^^^^^^^^   searchFunctionFactory parameter */
public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]> {
  /* searchFunctionFactory return value     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */

As comment notes, this is not Javascript syntax, but Typescript syntax.

So, if you call

const result = searchFunctionFactory(someVar);

result will be of the type

(text: Observable<string>) => Observable<any[]>

and you could then call it with

const resultTwo = result(someOtherVar)

to get a value whose type is Observable<any[]>.

Upvotes: 1

Related Questions