在 React TypeScript 中键入 useState 作为字符串数组

要在 React 中将 useState 钩子键入为字符串数组,请使用钩子的泛型,例如 const [names, setNames] = useState<string[]>([])。 状态变量可以初始化为空数组或字符串数组,并且只接受字符串值。

import {useState} from 'react';

const App = () => {
  // 👇️ const names: string[]
  const [names, setNames] = useState<string[]>([]);

  return (
    <div>
      <button onClick={() => setNames(prevNames => [...prevNames, 'Bob'])}>
        Add name
      </button>

      {names.map((element, index) => {
        return (
          <div key={index}>
            <h2>{element}</h2>
          </div>
        );
      })}
    </div>
  );
};

export default App;

我们使用泛型来正确键入 useState 钩子,同时使用空数组初始化钩子。

在 React TypeScript 中键入 useState 作为字符串数组

如果我们没有使用通用的,例如 useState<string[]>([]) 键入钩子时,状态变量的类型将是 never[],换句话说,一个永远不会包含任何元素的数组。

即使将一个空字符串传递给数组,TypeScript 也能推断出状态变量的类型。

import {useState} from 'react';

const App = () => {
  // 👇️ const names: string[]
  const [names, setNames] = useState(['']);

  return (
    <div>
      <button onClick={() => setNames(prevNames => [...prevNames, 'Bob'])}>
        Add name
      </button>

      {names.map((element, index) => {
        return (
          <div key={index}>
            <h2>{element}</h2>
          </div>
        );
      })}
    </div>
  );
};

export default App;

请注意 ,我们甚至不必使用泛型来键入状态变量。 TypeScript 能够根据提供的初始值推断类型。

但是,最好始终显式键入 useState 钩子,尤其是在使用数组和对象时。

如果我们尝试向状态数组添加不同类型的值,我们会得到类型检查错误。

import {useState} from 'react';

const App = () => {
  // 👇️ const names: string[]
  const [names, setNames] = useState<string[]>([]);

  // ⛔️ Argument of type '(prevNames: string[]) => (string | number)[]' is not
  // assignable to parameter of type 'SetStateAction<string[]>'.
  setNames(prevNames => [...prevNames, 1000]);

  return (
    <div>
      <button onClick={() => setNames(prevNames => [...prevNames, 'Bob'])}>
        Add name
      </button>

      {names.map((element, index) => {
        return (
          <div key={index}>
            <h2>{element.toUpperCase()}</h2>
          </div>
        );
      })}
    </div>
  );
};

export default App;

该示例显示尝试将数字添加到类型为 string[] 的状态数组如何导致类型检查器出错。