1

I am using react-typescript with vite. in my situation for arr interface I have option which is of type array of options or an array of strings. When I try to map and print them I am getting error on val.name which is

any
Property 'name' does not exist on type 'string | Options'.
  Property 'name' does not exist on type 'string'.ts(2339)

and on val

    (parameter) val: string | Options
Type 'string | Options' is not assignable to type 'ReactNode'.
  Type 'Options' is not assignable to type 'ReactNode'.ts(2322)
index.d.ts(1373, 9): The expected type comes from property 'children' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>'

How to solve this problem. Thanks in advance

import React from 'react';
interface Options {
    name: string;
}
interface arr {
    option: Options[] | string[];
}
const MapOfArrayHavingTwoDifferentTypes: React.FC<arr> = ({ option }) => {

    return (
        <>
            {
                option.length > 0 && option[0].hasOwnProperty("name") ?
                    option.map((val) => <p>{val.name}</p>) :
                    option.map((val) => <p>{val}</p>)
            }
        </>
    )
}

export default MapOfArrayHavingTwoDifferentTypes;

If the question helps please upvote it. Thank you

1 Answers1

1

Check the type inside the mapper function, not outside, for effective narrowing.

const MapOfArrayHavingTwoDifferentTypes: React.FC<arr> = ({ option }) => (
    <>
        {
            option.map(val => (
                <p>{typeof val === 'string' ? val : val.name}</p>
            ))
        }
    </>
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you very much. In between is there any possible way that we can do that outside map. – Ramu Sompalli Sep 02 '22 at 03:28
  • 1
    You would need a way to determine, at runtime, whether the array is an array of strings or an array of something else. Not impossible, but it'd be ugly and would either require an extraneous argument (like an `optionType` string, with the function overloaded to have the string match the array item type) or type assertions, which are smelly when not strictly necessary. Doing it inside the callback makes much more sense, I think. – CertainPerformance Sep 02 '22 at 03:37