Is it Observable or Not? Typescript Typehint helping you determine

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>'.

Full Example

Answer №1

Regarding test 3

Ob = string|number
However, it yields an Observable<string> which will never be a number (= Ob)

If you implement it this way

const observable_or_value = (test: string): Observable<string|number>|number => Math.random() > 0.5 ? of(test) : 42;
piped<string|number>(observable_or_value).pipe(map(x => x));

It resolves your issue as Ob will truly be string|number

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 11 along with RxJS does not support the combineLatest method in the specified type

Hey there, I'm currently working on utilizing the combineLatest operator to merge two streams in Angular, but I keep encountering an error message stating that "combineLatest does not exist on type". I've attempted to move the code into a .pipe() ...

What is the best way to utilize a tsconfig "alias path" to import an @ngModule along with other definitions?

Repository Link: https://github.com/andreElrico/mono-repo-test Stackblitz Example: https://stackblitz.com/github/andreElrico/mono-repo-test (noop; only to navigate smoothly) Assume the structure below: root/ ├── projects/ │ ├── app1 │ ...

Implementing a boolean toggle method in Typescript for a class property

Hello there, fellow programmers! I am interested in changing the value of a class field using a method. I have a button in Angular that, when clicked, triggers the onSave() method: export class CourseComponent { isActive:boolean; onSave() { ...

How can one break down enum values in typescript?

I've defined an enum in TypeScript as shown below: export enum XMPPElementName { state = "state", presence = "presence", iq = "iq", unreadCount = "uc", otherUserUnreadCount = "ouc", sequenc ...

Encountering a NPM error when trying to launch the server using ng serve

I encountered an error : ERROR in /opt/NodeJS/FutureDMS/src/app/app.module.ts (5,9): Module '"/opt/NodeJS/FutureDMS/src/app/app.routing"' has no exported member 'APP_ROUTE'. Within my code, I have utilized arrow function in the loadCh ...

Placing files in the "Dist" folder is causing an issue by disrupting the functionality of the Angular 2 app

For testing my login component in Angular2, I am using a mockBackend within my app. Initially, the standalone version of the login worked perfectly fine. However, when trying to integrate it into my ongoing development project, I encountered an issue. Duri ...

Encountering TS7053 error while trying to access component variables using type indexing in Angular 13

When trying to access a variable with type indexing in Angular 13, I encountered a TS7053 error. However, in this Stackblitz example, the same code works without any errors. export class AppComponent { name = 'Angular ' + VERSION.major; Pro ...

Scroll to the top on every Angular 5 route change

Currently, I am utilizing Angular 5 for my project. Within the dashboard interface, there are various sections with varying amounts of content. Some sections contain only a small amount of information, while others have large amounts of content. However, w ...

Angular 8: Implementing Form Validation with a Boolean Flag

Within my HTML code, I have a function (change)="limitUser($event)". In Typescript, I utilize a for loop to iterate through each element and determine if the value is less than 10. If it exceeds 10, the inValid = true condition is set. All form fields in m ...

The cache does not contain '.chunk-`X`' as requested in Next.js error

Hello everyone, I've encountered a recent issue with my code that previously worked fine. I was using getStaticProps with a cache time of 5 days, but now I'm facing an error related to the title. Here is a more detailed look at the error: error ...

Transfer all specified resources from one stack to another in AWS CDK

In the process of creating two stacks, I aim to reference the resources from the first stack, such as Lambda, API Gateway, and DynamoDB, in the second stack without hard coding all the resources using Stack Props. Please note: I do not want to use Stack Pr ...

An issue has been encountered in Angular while running the ng serve command, indicating that a certain module has not

import { MsalInterceptor } from '@azure/msal-angular/msal.interceptor'; Although the module has been declared without errors in VS Code, I am encountering an error in the command prompt stating that the module is not found. However, upon manual ...

"Encountered a TypeError while attempting to send a server action to a custom

My custom form component, <ClientForm>, is built using Radix Primitives. "use client"; import { FC } from "react"; import * as Form from "@radix-ui/react-form"; const ClientForm: FC = (props) => ( <Form.Root {.. ...

Can one obtain a public IP address using Typescript without relying on third-party links?

Though this question has been asked before, I am currently working on an Angular 4 application where I need to retrieve the public IP address of the user's system. I have searched on Stackoverflow for references, but most posts suggest consuming a th ...

The cancel function in lodash's debounce feature does not successfully halt the execution of the

In my angular application, I have implemented http calls on each modelChange event with the help of lodash's _.debounce(). However, I'm facing an issue where I am unable to cancel these calls after the initial successful execution of debounce. ...

Having trouble extracting parameters with TypeScript in React Router even when they are present

I am in the process of migrating an older project to utilize react and react-router. Additionally, I am fairly new to typescript, which is the language used for this particular project. Any guidance or explanations on these topics would be highly beneficia ...

Manipulating objects from an HTTP Observable while iterating through an Array of objects

I am currently working on processing each element of an array by making a separate HTTP call for each element. I need to track the status of each call and update the UI once all calls are completed. The code snippet below demonstrates my current approach: ...

Where's the tsconfig.json for Firebase Emulators?

I've encountered an issue with my Firebase project that's written in JavaScript (not TypeScript). When attempting to run the functions emulator, I'm getting the following error: $ firebase emulators:start --only functions ⚠ functions: Ca ...

Typescript error TS2717: All following property declarations should share the same data type

During development on my local host, the TypeScript build works perfectly fine. However, when transitioning to Docker with a Node image, I encounter a peculiar error during the build process: src/middlewares/auth.ts(16,13): error TS2717: Subsequent propert ...

Problem encountered with ESLint when utilizing babel module-resolver in conjunction with TypeScript

Typescript is not making type inferences with resolved imports, but it does with relative imports. Any assistance would be greatly appreciated. https://i.sstatic.net/2pgHX.png When using the 'useTheme' function, an error is displayed: "U ...