Home > Back-end >  Argument of type '(prevState: Stock[]) => (Stock | Stock[])[]' is not assignable to par
Argument of type '(prevState: Stock[]) => (Stock | Stock[])[]' is not assignable to par

Time:07-19

I am learning TypeScript and I am getting the below error. I am not able to understand hint provided by error. I have written this code without TypeScript and it works like charm. How to resolve this ??

Error Details

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)

Code


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;
        });
    }
 }

CodePudding user response:

The method setStockCollection should be decalred as below. Then it will show no erros in TypeScript.

         setStockCollection((prevState:Stock[]) => {
            let result:Stock[] = [ ...prevState, ...stockFromServer];
            return result;
        });

CodePudding user response:

You are forgetting to spread the stockFromServer array:

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;
    });
  };
};
  • Related