Home > Net >  Typescript error : Element implicitly has an 'any' type because expression of type 's
Typescript error : Element implicitly has an 'any' type because expression of type 's

Time:01-09

I'm new to typescript and I met an error I can't understand after finding an online tuto to sort data on Reactjs with react hooks. Here the part of my component code where I get the error :

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

Job.tsx :

export default function Jobs() {

const [data, setData] = useState([])
  const [sortType, setSortType] = useState('name')

  useEffect(() => {
    const sortArray = (type: string) => {
      const types = {
        jobName: 'jobName',
        created: 'created',
        modified: 'modified'
      }
      const sortProperty = types[type]
      const sorted = [...tasks].sort(
        (a, b) => new Date(b[sortProperty]) - new Date(a[sortProperty])
      )
      console.log(sorted)
      setData(sorted)
    }

    sortArray(sortType)
  }, [sortType])
  return (

            <div className="font-bold">Sort by:</div>
            <select
              onChange={(e) => setSortType(e.target.value)}
              className="text-center px-5 bg-gray-200 rounded-xl"
            >
              <option value="id">Id</option>
              <option value="jobName">Job name</option>
              <option value="created">Newest</option>
              <option value="modified">Last modified</option>
            </select>
            <div>({tasks.length} users)</div>

   {data.map((task) => (
                <tr
                  key={task.id}
                  className="tableau text-center cursor-pointer"
                  onClick={() => router.push(`/job/${task.id}`)}
                >
                  <td className="py-3">{task.jobName}</td>
                  <td className="py-3">
                    <div className="flex items-center gap-5 justify-center">
                      {task.created}
                    </div>
                  </td>
                  <td className="py-3">
                    <div className="flex items-center gap-5 justify-center">
                      {task.modified}
                    </div>
                  </td>
              ))}
)
}

CodePudding user response:

The error message is telling you that the type of the sortProperty variable is string, but it is being used to index into an object. So you will need to update the types object to have an index signature like this

interface StringIndexedObject {
    [key: string]: string;
}


const types: StringIndexedObject = {
    jobName: 'jobName',
    created: 'created',
    modified: 'modified',
};

This will allow you to use a string to index into the types object and the correct type will be inferred for the resulting value.

  • Related