I'm currently facing issues with my React and Typescript project. Specifically, I encounter problems when dealing with variables that are initially set to null and will later receive asynchronous data of a certain type.
For instance, let's say I have an AdminBlogPostPage
where the admin can create and edit posts. There's a variable used to store the blog post data, which starts off as null because the post will be loaded asynchronously.
To handle this scenario under strict null checks, I define the type like this:
type ADMIN_BLOGPOST_STATE = {
blogPost: null | BLOGPOST
}
The blogPost
state transitions from being null to holding a BLOGPOST
once loaded. Although functional, it leads to inconvenience as Typescript constantly worries about potential null values for blogPost
.
In such cases, I typically use Redux and find myself repeatedly performing type assertions in my reducers to clarify to Typescript that after certain actions, blogPost
is guaranteed to be a BLOGPOST
and not null.
How do others manage the typing for asynchronous data? Is it better to start with null and update it later or begin with a valid blogPost: BLOGPOST
stub as the initial state to avoid repetitive type assertions?
Note: Even if I opt for the latter approach, whereby blogPost
is initialized as a BLOGPOST
, I still need to fetch data from the database. The initial state serves merely to indicate to Typescript that blogPost
will always be a BLOGPOST
.