Observable <any>不能分配给Observable <any>

时间:2018-03-21 08:15:08

标签: angular typescript ionic3 observable

我使用角度5和离子3。 我有一个界面:

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

实现此接口的组件具有方法:

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

这个方法应该返回不同类型的dataSources,有时候它会是简单的字符串数组,有些时间是对象数组,有些时候是简单对象。

有可能吗?

3 个答案:

答案 0 :(得分:4)

这是可能的,但您不需要将数组转换为any

如果不这样做,在您的示例中,您的函数类型为() => Observable<string>,类型与() => Observable<any>兼容,这是接口中定义的方法的类型。

我的意思是,如果你有:

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

然后你可以这样做:

a = b;

因为any与TypeScript中的任何类型兼容。

答案 1 :(得分:2)

你有几种方法可以做到这一点:

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

一切都应该有用。您只需将any替换为您的类型即可。

顺便说一下,你的界面应该是这个

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

您声明一个函数,而不是一个变量。

更好,正如@nicowernli建议的那样,如果你想动态输入你的回报,请用泛型类型声明你的界面和你的函数:

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

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

答案 2 :(得分:1)

如果你像我一样,并希望尽可能避免“任何”类型(在这种情况下你的任何铸件),你可以使用Type Alias特别为你的价值。

看起来像这样:

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

您可以在TS Docs

找到有关类型别名的所有内容

您甚至可以更进一步,用您的自定义类型替换通用对象类型。

相关问题