Looking for some guidance from the experts: Is there a way to simplify the function overload in the example below by removing as Observable<string[]>
and using T and T[] instead?
Here's a basic example to illustrate:
import { Observable } from 'rxjs';
class Test<T> {
test(flag : string) : Observable<T>;
test(flag : string) : Observable<T[]>;
test(flag : string) : Observable<T | T[]>
{
if (flag === 'foo')
{
return new Observable<T>();
}
return new Observable<T[]>();
}
}
const test : Test<string | string[]> = new Test();
test.test('foo');
(test.test('bar') as Observable<string[]>).subscribe(foo => foo.map(bar => bar));
Now, let's explore a real-world Angular scenario:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { OptionWithBodyInterface } from './common.interface';
import { CommonService } from './common.service';
import { MethodType } from './common.type';
import { createUrl } from './helper';
@Injectable()
export class RequestService<T> extends CommonService
{
public request(method : MethodType, options? : OptionWithBodyInterface) : Observable<T | T[]>
{
return this.http.request<T | T[]>(method, createUrl(this.getApiUrl(), this.getEndpoint()),
{
...this.getOptions(),
...options
});
}
}