Home > Back-end >  TypeScript gives error when calling .size on a map in React
TypeScript gives error when calling .size on a map in React

Time:06-02

I'm writing a React Component where I pass a map in as a prop and read the size of it later. When I type the map with TypeScript, I get no errors, but I get an error when I call .size on the map. In addition, when I try to map over that array, I get an error as well.

The map itself contains key and value pairs, both of which are strings.

Code:

import * as Styled from './assignments-list.styles'

type TMap<T> = {
    [index: string] : T
}

type TAssignmentsListProps = {
    assignments: TMap<string>
}

const AssignmentsList = ({assignments}: TAssignmentsListProps) => {

    return (
        <Styled.AssignmentsList>
            <Styled.Header> 
                Assignments
            </Styled.Header>
                {
                    (assignments && assignments.size !== 0) ? // error here
                    <Styled.ListFiles>
                        {
                            Array.from(assignments).map(([name, url]) => { // error here
                                return (
                                    <li key={name}> 
                                        <Styled.ListItemWrapper>
                                            <Styled.FileName>
                                                {name}
                                            </Styled.FileName>
                                            <Styled.RemoveFile>
                                                View
                                            </Styled.RemoveFile>
                                        </Styled.ListItemWrapper>
                                    </li>
                                )
                            })
                        }
                    </Styled.ListFiles> :
                    <Styled.BodyText>None</Styled.BodyText>
                }
        </Styled.AssignmentsList>
    )
}

export default AssignmentsList

Any ideas?

CodePudding user response:

I don't understand what is the real type of the assignments

Here error assignments.size !== 0 because you are trying to compare a string with a number, which is always false.

If can be fixed, by fixing type


type TMap<T> = {
  [index: string]: T
} & {
  size: number
}

or


type TMap<T> = Map<string, T>

Or if it map of string, you can check map size with


assignments && Object.keys(assignments).length !== 0

Converting your map to array depending on real map type. If it Map then Array.from should work

If it map of string you can use How to convert an Object {} to an Array [] of key-value pairs in JavaScript

  • Related