[Solved] Smart assuming of variable type


You can use
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

But you need to pass the variable

const isLoaded = (response: ResponseData | undefined): response is ResponseData => {
    // some complex logic to check if the data is loaded and correct
    return !isLoading && !!data && Object.keys(data).length > 0
}


return (
    <>
        <div>My data title:</div>
        {isLoaded(data) && <div>{data.title}</div>} // error! data could be "undefined"
    </>
)

But I would personally use the isLoaded state for that and force data always to have value (and errors too):

const [error, setError] = useState<string>();
const [data, setData] = useState<ResponseData>({} as ResponseData);
const [isLoading, setIsLoading] = useState<boolean>(true);

return (
    <>
        <div>My data title:</div>
        {isLoading && <div>Data is loading</div>}
        {error && <div>Error loading data. {error} </div>}
        {!isLoading && !isError && <div>{data.title}</div>}
    </>
)

solved Smart assuming of variable type