Search code examples
angulartypescriptangular2-observables

Angular 2 & Typescript Observable Function Parameter - What Does Pipe Do?


Recently I had a need to take an Observer parameter in a function, and I was banging my head on my desk trying to figure out how to do this in Typescript. You might recall taking a delegate parameter in C#; that's basically what I was trying to do here. This was part of a subscribe(observer: Observer<any>). The reason I was doing this is because I was trying to add an AOP type of bookend for subscriptions. That's not the important part.

Basically to get this to work, you have to add a | character behind your function parameter, and it ends up like this:

(observer: Observer<any> | ((value: any) => void)): void

My question basically is what does the bold part do in that function signature? I've scoured every resource I can think of but can't figure it out. Without the portion after the |, I was getting this error:

Argument of type '(res: any) => void' is not assignable to parameter of type 'Observer'. Property 'next' is missing in type '(res: any) => void'.

Once I added the pipe character and portion after, I was able to subscribe without issue in the traditional observer way (using an arrow function), and I have also confirmed that all subscriptions work (which rules out the portion after the pipe being a default value). Any ideas would be appreciated, because I hate seeing something work but having no idea why!


Solution

  • It means the observer is of type Observer<any>

    |(or)

    ((value: any) => void) : A function whose input is any value and output is void.