Home > Mobile >  Object is of type 'unknown'
Object is of type 'unknown'

Time:12-20

I have simple Rxjs function Observables and Operators to return new Observable.in my code i am using filter and map operators chained inside a pipe sadly, i get error TS2571: Object is of type 'unknown'. inside filter operator data The code is following :

import { filter, map, Observable } from 'rxjs'

@Component({
  selector: 'app-observable-operator',
  templateUrl: './observable-operator.component.html',
  styleUrls: ['./observable-operator.component.css']
})
export class ObservableOperatorComponent{

  title:string='Angular Observable using Observable Operators';

  ob=new Observable((observer:any)=>{
    console.log("Observable Starts");
    observer.next(1)
    observer.next(2)
    observer.next(3)
    observer.next(4)
    observer.next(5)
    observer.complete()
  }).pipe(filter(data=>
    data > 2), //Error inside filter operator (parameter) data:unknown
    map((val)=>{return val as number*2}),

  )

}


CodePudding user response:

I believe you need to add typing to the param

filter((data: any) => data > 2)

CodePudding user response:

The way to fix this issue is to define the type of the observer right.

The observer parameter in the function passed to the constructor of the Observable is of type Observer<number>, since it notifies numbers. If you do this, Typescript can infer the type of data as number.

In other words the code should be this

ob=new Observable((observer: Observer<number>)=>{
  console.log("Observable Starts");
  observer.next(1)
  observer.next(2)
  observer.next(3)
  observer.next(4)
  observer.next(5)
  observer.complete()
}).pipe(filter(data=>
  data > 2), //Error inside filter operator (parameter) data:unknown
  map((val)=>{return val as number*2}),

)
  • Related