Home > Blockchain >  When using type script if one array have two different type of values, How to have two different map
When using type script if one array have two different type of values, How to have two different map

Time:09-02

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;

CodePudding user response:

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>
            ))
        }
    </>
);
  • Related