Home > Software design >  useRef typescript 'string' can't be used to index type '{}'
useRef typescript 'string' can't be used to index type '{}'

Time:08-11

I've an issue using typescript with useRef:

 <div ref={(el) => (listRef.current[v.name] = el)}>{v.name}</div>

v.name is a string and it doesn't work for my interface:

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

I got error of No index signature with a parameter of type 'string' was found on type '{} | listRefObj'

https://codesandbox.io/s/react-typescript-forked-8fnog1?file=/src/App.tsx

CodePudding user response:

In your code el can be HTMLDivElement | null (and not string). So the correct annotation should be:

interface listRefObj {
  [key: string]: HTMLDivElement | null;
}

Also the ref type needs to be just listRefObj i.e. useRef<listRefObj>({})

Complete code

import React, { useRef } from "react";
import "./styles.css";

interface listRefObj {
  [key: string]: HTMLDivElement | null;
}

export default function App() {
  const listRef = useRef<listRefObj>({});

  const result = [
    {
      id: 1,
      name: "apple"
    },
    {
      id: 2,
      name: "orange"
    }
  ];

  return (
    <div className="App">
      {result.map((v) => (
        <div ref={(el) => (listRef.current[v.name] = el)}>{v.name}</div>
      ))}
    </div>
  );
}
  • Related