我有以下用于在Typescript中练习rxJS的简单代码。
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();
为什么命令提示符会引发错误?
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))
~~~~~~
...
我认为代码应该可以工作,因为return from<Promise<{userId: number}>>{...
中已经定义了userId
VScode还给我与 userId 相关的错误消息
Property 'userId' does not exist on type 'unknown'.ts(2339)
答案 0 :(得分:4)
请在下面尝试。
替换
v.userId
收件人
v['userId']