Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react hooks and typescript - Property '***' does not exist on type 'never'

I have come across this from numerous angles, and currently my code looks like this, and I get the following error:

Property 'albums' does not exist on type 'never'

I am using React hooks, but getting an error from the data object updated with useState. data has an property albums that I am not sure how to define, or where to do this.

import React, { useState } from 'react';

interface ArtistProps {
   artistName: string,
}


const Artist: React.SFC< ArtistProps > = ({ artistName }) => {

    const [data, setData] = useState(null);

    return (
        <>
            <p>{artistName)}</p> // this is fine
            <p>{data.albums}</p> // error here
        </>
    );
}
like image 426
peter flanagan Avatar asked Dec 03 '18 17:12

peter flanagan


1 Answers

Try this:

const [data, setData] = useState<null | {albums: any}>(null);

Then use the data variable like

data!.albums 

The ! is to let typescript know that you're sure the value is not null. But even better is to explicitely check the value for null e.g. data ? data.albums : 'no data'

P.S. Instead of {albums: any} add your appropriate inerface.

like image 162
Nurbol Alpysbayev Avatar answered Sep 29 '22 16:09

Nurbol Alpysbayev