Milos
Milos

Reputation: 1848

Observable<any> is not assignable to type Observable<any>

I am using angular 5 with ionic 3. I have one interface:

export interface IAny {
    getDataSource: Observable<any>;
}

Components which implements this interface has method:

getDataSource () {
      return Observable.of(['Item1', 'Item2', 'Item3'] as any)
 };

This method should return different types of dataSources, some time it will be simple array of string , some time array of objects, some time the simple object.

Is it possible at all ?

Upvotes: 1

Views: 721

Answers (3)

user4676340
user4676340

Reputation:

You have several way of doing this :

return Observable.of<any>(['Item1', 'Item2', 'Item3'])
return Observable.of(['Item1', 'Item2', 'Item3']) as any
return Observable.of(['Item1', 'Item2', 'Item3']) as Observable<any> // For code completion

All should work. You can just replace any with your type.

By the way, your interface should be this

export interface IAny {
    getDataSource(): Observable<any>;
}

You declare a function, not a variable.

Better, as @nicowernli suggested, if you want to type your returns on the fly, declare your interface and your functions with generic types :

export interface IAny {
  getDataSource<T>(): Observable<T>;
}

getDataSource<T>() {
  return Observable.of(['Item1', 'Item2', 'Item3'] as any)
};

Upvotes: 2

Nicolas Gehlert
Nicolas Gehlert

Reputation: 3253

If you are like me and want to avoid the 'any' type as much as possible (and in this case your any-castings) you could use a Type Alias especially for your value.

It could look something like this:

// Just add your desired types that are possible return values
type DataSourceType = Array<string> | Array<object> | object;

You find everything about Type Aliases at the TS Docs

You could even take it one step further and replace the generic object type with your custom type.

Upvotes: 1

Oscar Paz
Oscar Paz

Reputation: 18292

It is possible, but you don't need to cast the array to any.

If you don't, in your example, your function is of type () => Observable<string>, a type compatible with () => Observable<any>, which is the type of the method defined in the interface.

I mean, if you have:

let a: () => Observable<any>;
let b: () => Observable<string>;

Then you can do:

a = b;

Because any is compatible with any type in TypeScript.

Upvotes: 4

Related Questions