Daino
Daino

Reputation: 53

Typescript - Property 'userId' does not exist on type 'unknown'

I have the following simple code for practicing rxJS in Typescript.

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 does the command prompt throws an error?

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 thought the code should work because the userId is already defined in return from<Promise<{userId: number}>>{...

VScode also gives me the error message related with the userId Property 'userId' does not exist on type 'unknown'.ts(2339)

Upvotes: 5

Views: 6805

Answers (1)

Raj
Raj

Reputation: 638

Please try below.

Replace

v.userId

To

v['userId']

Upvotes: 12

Related Questions