Typescript: The property 'userId' is not found within the 'unknown' type

For my rxJS practice in Typescript, I wrote the following simple code.

import fetch from 'node-fetch';
import {
    Observable, Subject, asapScheduler, pipe, of, from,
    interval, merge, fromEvent, SubscriptionLike, PartialObserver
} from 'rxjs';
import { map, filter, scan } from 'rxjs/operators';

function getUserId() {
    return from<Promise<{userId: number}>>(
        fetch('https://jsonplaceholder.typicode.com/posts/1').then(r => r.json())
    )
    .pipe(map(v => v.userId))
    .subscribe(console.log);
}

getUserId();

Why am I getting an error in the command prompt?

C:\Users\Administrator\Downloads\typescript>ts-node from.ts

C:\Users\Administrator\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:423

    return new TSError(diagnosticText, diagnosticCodes)
           ^
TSError: ⨯ Unable to compile TypeScript:
from.ts:12:22 - error TS2339: Property 'userId' does not exist on type 'unknown'
.

12     .pipe(map(v => v.userId))
                        ~~~~~~
...

I was expecting the code to work since the userId is defined in

return from<Promise<{userId: number}>>{...

VScode also gives me the error message regarding the userId

Property 'userId' does not exist on type 'unknown'.ts(2339)

Answer №1

Kindly attempt the steps provided below.

Substitute

v.userId

With

v['userId']

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

Showing Information without NgFor Directives

I have successfully displayed data without using a ngFor loop. However, it is currently showing all the quote information from multiple customers. The CSS is arranged in such a way that the discount div is positioned next to the customerinfo div. Below is ...

Typescript Declarations for OpenLayers version 6

The package @types/openlayers found at https://www.npmjs.com/package/@types/openlayers only provides type definitions for version 4.6 of OpenLayers. This is clearly stated in the top comment within the file index.d.ts. If types for OpenLayers 6 are not av ...

"Troubleshooting: Why are my Webpack 2 stylesheets

Recently, I made an update to my application (currently running on [email protected]) by switching from Webpack 1.x to Webpack 2.6.1. Despite following the migration documentation, upon running the application, the external stylesheets fail to load. M ...

Issue: In an Angular electron app, a ReferenceError is thrown indicating that 'cv' is

I have been working on a face detection app using OpenCv.js within an Angular electron application. To implement this, I decided to utilize the ng-open-cv module from npm modules. However, when attempting to inject the NgOpenCVService into the constructor ...

Guide to encapsulating an asynchronous function in a promise

I am in need of wrapping an asynchronous function within a promise to ensure synchronous execution. The reason behind this is that I must obtain a result from the asynchronous function before proceeding with the program's execution. Below is the rele ...

Edge is experiencing a slowdown when utilizing ng-bind-html

I've been using ng-bind-html to bind HTML content to a div element. However, when I attempt to bind larger amounts of HTML, it can take around 5-6 seconds for the content to load. Interestingly, this issue seems to only occur in Chrome browser. I have ...

Exploring the functionality of generic components in React Native when using TypeScript

As an illustration, consider export class FlatList<ItemT> extends React.Component<FlatListProps<ItemT>> which incorporates the generic type ItemT. How can I utilize it in a .tsx code? When not parametrized, it appears like this: <Flat ...

Template reference does not connect to the ApexChart graphic

As a newcomer to ApexCharts.js, I am currently working on setting up a Vue3 app using Composition API along with the setup syntax. My goal is to reference the template ref of 'apexchart' so that I can later call the dataURI() function on it. I am ...

Attempting to develop a server component that will transmit a JSON result set from a MySQL database located on the local server. What is the best method to send the server object (RowDataPacket) to the

After successfully rendering server-side pages and creating forms with react hooks for database updates, I encountered a challenge in integrating Ag-Grid into my application. Despite being able to retrieve data from the database using the mysql2 module and ...

Typescript: Delay code execution until a function has completed running

I've encountered an issue with my code that involves calling a function. Here is the snippet of code in question: this.getAllOptions(questionID); console.log("++++++++++++++++++++++++++++++++"); console.log(this.result); The task of this function is ...

Struggling with defining types in NextJs when using dynamic imports in Typescript and NextJs

I have successfully created a component that utilizes next/dynamic to import react-icons only when needed. However, I am struggling to properly define the TypeScript types for this component. Despite this issue, the component itself is functioning as expec ...

Obtain the popup URL following a fresh request using JavaScript with Playwright

I'm having trouble with a button on my page that opens a popup in a new tab. I have set up a listener to capture the URL of the popup when it opens: page.on('popup', async popup => { console.log('popup => ' + await pop ...

What is the process of substituting types in typescript?

Imagine I have the following: type Person = { name: string hobbies: Array<string> } and then this: const people: Array<Person> = [{name: "rich", age: 28}] How can I add an age AND replace hobbies with a different type (Array< ...

TypeORM - Establishing dual Foreign Keys within a single table that point to the identical Primary Key

Currently, I am working with TypeORM 0.3.10 on a project that uses Postgres. One issue I encountered is while trying to generate and execute a Migration using ts-node-commonjs. The problem arises when two Foreign Keys within the same table are referencing ...

Error message in Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object.' NgFor is only able to bind to iterables like Arrays

When making an API call in my Angular project, I receive the following JSON response: { "data": { "success": true, "historical": true, "date": "2022-01-01", "base": "MXN&quo ...

It is not possible to transform Next.js into a Progressive Web App (P

Can someone assist me with PWA implementation? I tried running npm run build, but it was unsuccessful. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdbaacbface0abbfa2a3b98dfde3fce3fd">[email protected]</a> ...

How can I add a dropdown filter to column values in ag-grid?

I'm attempting to implement a dropdown filter for a column in an ag-grid using Angular 8. I've successfully displayed the column with the following code: columnDefs = [ { headerName: 'Id' , field: 'id' ...

Proper Input Component Typing in React/Typescript with MobX

Looking to create a custom React Input component using Typescript for MobX that requires the following input props: a mobx store stateObject a key from that store stateKey I want Typescript to ensure that stateObject[stateKey] is specifically of type str ...

Guide to customizing the layout preview specifically for certain components in Storybook, without affecting all components

Currently working on my storybook project and facing an issue. I'm aiming to have the layout centered in the preview section. I attempted export const parameters = { layout: 'centered', }; in the .storybook/preview.js file However, this c ...

Toastr service experiencing issues on Internet Explorer browser

While implementing toastr notifications in my Angular application, I encountered an issue with compatibility across browsers. Specifically, the ngx-toastr module functions properly in Chrome and Firefox, but not in Internet Explorer. Interestingly, it wo ...