我正在学习TypeScript,我得到下面的错误。我听不懂错误提示。我在没有TypeScript的情况下编写了这段代码,它的工作效果非常好。如何解决这个问题?
错误详细信息:
Argument of type '(prevState: Stock[]) => (Stock | Stock[])[]' is not assignable to parameter of type 'SetStateAction<Stock[]>'.
Type '(prevState: Stock[]) => (Stock | Stock[])[]' is not assignable to type '(prevState: Stock[]) => Stock[]'.
Type '(Stock | Stock[])[]' is not assignable to type 'Stock[]'.
Type 'Stock | Stock[]' is not assignable to type 'Stock'.
Type 'Stock[]' is missing the following properties from type 'Stock': ticker, name, price, change, and 2 more.ts(2345)
代码:
export interface Stock {
ticker: string;
name: string;
price: string;
change: string;
percentChange: string;
id: string;
}
export const PlayGroundWebsockets: React.FunctionComponent<unknown> = (
props: unknown
) => {
let stockFromServer: Stock[] = [];
const [stockCollection, setStockCollection] = useState<Stock[]>([]);
const displayStocks = () => {
setStockCollection((prevState: Stock[]) => { // <- Error from here
let result = [...prevState, stockFromServer];
return result;
});
};
};
setStockCollection方法的声明如下:然后它就不会在TypeScript中显示错误了。
setStockCollection((prevState:Stock[]) => {
let result:Stock[] = [ ...prevState, ...stockFromServer];
return result;
});
您忘记展开stockFromServer
数组:
export const PlayGroundWebsockets: React.FunctionComponent<unknown> = (
props: unknown
) => {
let stockFromServer: Stock[] = [];
const [stockCollection, setStockCollection] = useState<Stock[]>([]);
const displayStocks = () => {
setStockCollection((prevState: Stock[]) => {
// let result = [...prevState, stockFromServer]; <- Before
let result = [...prevState, ...stockFromServer];
return result;
});
};
};