I'm facing an issue while writing a function with correct typehints. It seems to work fine with explicit type hinting but breaks down when trying to use automatic type hinting. Can someone please help me identify the error in my code and suggest how I can modify the function so that Test 4 compiles as intended?
type NotObservable<T> = T extends (Observable<unknown>|Observable<unknown>[]) ? never : T;
function piped<Ob>(fn: (value: string) => (Observable<Ob>|NotObservable<Ob>)): Observable<Ob>{…}
// Test 1: number
const valueF = (test: string): number => 42;
piped(valueF).pipe(map(x => x));
// works - x is typeof number
// Test 2: Observable<string>
const observable = (test: string): Observable<string> => of(test);
piped(observable).pipe(map(x => x));
// works - x is typeof string
// Test 3: Observable<string>|number WITH explicit typthint
const observable_or_value = (test: string): Observable<string>|number => Math.random() > 0.5 ? of(test) : 42;
piped<string|number>(observable_or_value).pipe(map(x => x));
// works - x is typeof string|number
// Test 4: … without explicit typehint
piped(observable_or_value).pipe(map(x => x));
// error:
// Argument of type '(test: string) => Observable<string> | number' is not assignable to parameter of type '(value: string) => string | Observable<string>'.
// Type 'number | Observable<string>' is not assignable to type 'string | Observable<string>'.
// Type 'number' is not assignable to type 'string | Observable<string>'.