'problème de variable never

I created a React Component because I have a problem with a "never" variable.

There's the component code :

import React from "react";

class User {
    id: number
    name: string

    constructor(id: number, name: string) {
        this.id = id;
        this.name = name;
    }

    getAccounts = () => {
        console.log("getAccounts");
    }
}

export default class TestComponent extends React.Component<
    {},
    {
        user: null | User
    }
> {
    state = {
        user: null
    }

    componentDidMount = () => {
        this.setState({
            user: new User(1, "re")
        }, this.getActiveUserAccounts)
    }

    getActiveUserAccounts = async () => {
        let activeUser = this.state.user;

        console.log("activeUser", activeUser);

        if (activeUser !== null) {
            await activeUser.getAccounts();
        }
    }

    render(): React.ReactNode {
        return (
            <div id="test_component">
                <h1>Test</h1>
            </div>
        )
    }
}

First, I create the User class.

Then, I create the Test Component. I start state with an objet with the user key which can be null or User. I initiate user with null.

In the componentDidMount method, I update the state, I modify the user key to be an User. When the state is updated, I call getActiveUserAccounts.

At this time, the variable activeUser is an User, I can see it in the console. But if I unquote the line getAccounts(), I got an error which say the activeUser is type never. The compiler thinks activeUser can only be equal to null.

Can you tell me if I did something wrong or if there's a workaround ?

Thank you for the support



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source