CodexBloom - Programming Q&A Platform

Handling Union Types in TypeScript with Conditional Logic in a React Component

πŸ‘€ Views: 1345 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
typescript react type-guards

I've been researching this but I'm following best practices but I'm working on a React component where I need to handle a prop that can either be an array of strings or a string. Based on the type of this prop, I want to display the data differently. I have defined my prop types using a union type, but I'm running into issues with TypeScript not inferring the types correctly when I try to use conditional logic within the render method. Here's what I have: ```typescript import React from 'react'; type MyComponentProps = { items: string | string[]; }; const MyComponent: React.FC<MyComponentProps> = ({ items }) => { // TypeScript is giving an behavior here if (Array.isArray(items)) { return <ul>{items.map(item => <li key={item}>{item}</li>)}</ul>; } else { return <p>{items}</p>; } }; export default MyComponent; ``` When I run this code, I get the following behavior message: ``` Type 'string' is not assignable to type 'never'. ``` I followed the TypeScript documentation about type guards but it seems like the inference isn't working as expected. I have tried using the `typeof` operator and even created a custom type guard function, but nothing seems to resolve the scenario. Here’s what I attempted for the custom type guard: ```typescript function isStringArray(items: string | string[]): items is string[] { return Array.isArray(items); } ``` And then I modified my component like this: ```typescript const MyComponent: React.FC<MyComponentProps> = ({ items }) => { if (isStringArray(items)) { return <ul>{items.map(item => <li key={item}>{item}</li>)}</ul>; } else { return <p>{items}</p>; } }; ``` Yet, I still encounter the same behavior. Any insights on how to properly handle this union type and ensure TypeScript understands the condition correctly? I'm currently using TypeScript version 4.5.4 and React 17.0.2. The project is a web app built with Typescript. Cheers for any assistance!