Home > Back-end >  How to cast to specific object type in Typescript?
How to cast to specific object type in Typescript?

Time:01-14

I'm new to Typescript/React/rxJS ecosystem.

I use the following code snippet in my React/Typescript/rxJS application to download a list of users for my proof of concept work:

        const githubUsers = `https://api.github.com/users?per_page=1`;
    
        const users$ = ajax.getJSON(githubUsers).pipe(
            map(response => {
                // @ts-ignore
                const user: User = response[0] as User;
                return user;
            }),
            catchError(error => throwError(error))
        );
    
        users$.subscribe(
            response => log.info("User response: ", response),
            error => log.error(error),
            () => log.info("Subscription completed.")
        );

The "log.info" is my custom built log framework, it can be replaced with "console.log" if you want to try it out.

If I leave the "ts-ignore", I have this problem:

TS2571: Object is of type 'unknown'.
    72 |         const users$ = ajax.getJSON(githubUsers).pipe(
    73 |             map(response => {
  > 74 |                 const user: User = response[0] as User;
       |                                    ^^^^^^^^
    75 |                 return user;
    76 |             }),
    77 |             catchError(error => throwError(error))

So, my question is how can I properly cast this?

I appreciate any help on this.

CodePudding user response:

The problem is already in the logs

  •  Tags:  
  • Related