在打字稿中,出现以下错误:Type 'string[]' is not assignable to type 'never[]'.
我想将'abc'添加到数组中,这怎么了?
export default function App() {
const [text, setText] = React.useState("abc");
const [arr, setArr] = React.useState([]);
const xx = () => setArr([...arr, text]);
return <div className="App">{text}</div>;
}
https://codesandbox.io/s/boring-spence-08g8r?file=/src/App.tsx:56-272
const initArr: string[] = [];
const [text, setText] = React.useState("abc");
const [arr, setArr] = React.useState(initArr);
仅尝试定义您的初始化数组
const [arr, setArr] = React.useState([] as string[]);
编译器需要知道数组的类型。
在第二个useState语句中定义数组的类型,
喜欢:const [arr, setArr] = React.useState<string[]>([]);