JavaScript Typescript, type stimmt nicht

Hendoul

Commander
Registriert
Apr. 2008
Beiträge
2.158
Hi :)

Javascript:
type Blub = {
    payload: Course[]
}

const http$: Observable<Course[]> = createHttpObservable('/api/courses');

const courses$ = http$.pipe(
    map((json: Blub) => Object.values(json.payload))
);

Bei
Code:
json: Blub
gibt es ein Problem:
TS2345: Argument of type 'OperatorFunction<Blub, Course[]>' is not assignable to parameter of type 'OperatorFunction<Course[], Course[]>'. Type 'Blub' is missing the following properties from type 'Course[]': length, pop, push, concat, and 26 more.

Aber ich verstehe nicht warum.

Die Response sieht so aus:
JSON:
{"payload":[{"id":0,"description":"RxJs In Practice Course","iconUrl":"xyz.png","courseListIcon":"xyz.png","longDescription":"Understand the RxJs Observable pattern, learn the RxJs Operators via practical examples","category":"BEGINNER","lessonsCount":10},...
 
Hendoul schrieb:
Aber ich verstehe nicht warum.
Course[] und Blub sind nicht der gleiche Typ.

In Zeile 5 erzählst du TypeScript, dass du Course[] bekommst, aber in Zeile 8 schreibst du, dass du Blub erwartest.

Wenn die Response tatsächlich so aussieht, musst du wohl Zeile 5 anpassen.
 
Stimmt, das ist dann wohl auch ein Fehler im Kurs den ich da grad mache.
Dort wird es einfach umgangen/verschleiert, in dem nicht json.payload verwendet wird, sondern json['payload']...

Habe testweise jetzt mal kurz ein neues Interface definiert:
Javascript:
const http$: Observable<PayloadCourse> = createHttpObservable('/api/courses');

const courses$ = http$.pipe(
    map((json: PayloadCourse) => Object.values(json.payload))
);
 
Geht nicht, wenn der index type nicht explizit string ist.
 
Zurück
Oben