Home > Back-end >  Typescript with conditional type on Map function
Typescript with conditional type on Map function

Time:06-06

Hello i'm abit stuck with typescript. I have an array of 2 possible types because I would like to render conditional component based on the type. I am not sure how to check for that. Here is what I have so far:

 {sectionedListItems.map(
            (item: TypeDataEntityTypePost | TypeSection) => {
              if (item is TypeSection) {
                return <Typography>{item.title}</Typography>;
              }
              const postItem = item as TypeDataEntityTypePost;
              return <PostItem post={postItem} key={postItem.id} />;
            }
          )}

CodePudding user response:

If there is a title property in TypeSection but not in TypeDataEntityTypePost, then you can simply do this:

  {sectionedListItems.map((item: TypeDataEntityTypePost | TypeSection) => {
    if ('title' in item) return <Typography>{item.title}</Typography>
    return <PostItem post={item} key={item.id} />
  })}

There is no need of the as-cast too. TypeScript will treat item in any statement outside that block as TypeDataEntityTypePost. Type guarding using the in operator is supported in TS 2.7 and above. Reference.

Documentation.

CodePudding user response:

Let change:

if (item is TypeSection)

to

if (item instanceof TypeSection)
  • Related