Search code examples
reactjstypescripttypescript-genericsreact-typescript

How to set a type object as initial value of React using Typescript and useState?


I just started learning build React apps with Typescript and I'm really stuck at this point.

I set a type to be the model of a state, but I'm getting this error:

enter image description here

This is what I'm doing:

type TAssetsOverview = {
    totalAssets: number,
    assetsInOperation: number,
    assetsInAlert: number,
    assetsInDowntime: number
}

const AssetsOverview: React.FC = () => {
    const [overview, setOverview] = React.useState<TAssetsOverview>({})
    return (
        <div>
            <AssetsList assets={assets} />
        </div>
    )
}

export default AssetsOverview

What I want to do is to set overview as an object based on type TAssetsOverview.

I tried to set the values within the object, like this:

const [overview, setOverview] = React.useState<TAssetsOverview>({
        totalAssets, 
        assetsInOperation, 
        assetsInAlert, 
        assetsInDowntime
    })

But I get this error:

enter image description here

If I remove type TAssetsOverview and just set useState<{}>({}) it works fine, but I guess that's not how it should be done.

From where I see it looks exactly like all the tutorials and articles I read, but since I'm a newbie I can't see what is missing here.

How should I set this?


Solution

  • You need a default value which must corresponds to TAssetsOverview:

    In your case as the variables are numbers you can set it default to 0 if that helps your cause.

    type TAssetsOverview = {
        totalAssets: number,
        assetsInOperation: number,
        assetsInAlert: number,
        assetsInDowntime: number
    }
    
    const AssetsOverview: React.FC = () => {
        const [overview, setOverview] = React.useState<TAssetsOverview>({
        totalAssets: 0,
        assetsInOperation: 0,
        assetsInAlert: 0,
        assetsInDowntime: 0
    })
        return (
            <div>
                <AssetsList assets={assets} />
            </div>
        )
    }
    
    export default AssetsOverview