1

Hey I'm pretty new to typescript and I have a piece of state that I'm trying to alter in a child component based on the previous value but, I keep getting a type error when calling the setState function.

This is the function type

setPlayerCounts?: React.Dispatch<React.SetStateAction<number[]>>;

This is where I'm getting an error on the parameter of setPlayerCounts

if(setPlayerCounts && playerCount !== undefined)
      setPlayerCounts(prev => prev ? [...prev, playerCount] : [playerCount]);

Error:

Argument of type '(prev: number[]) => (number | undefined)[]' is not assignable to parameter of type 'SetStateAction<number[]>'.

Type '(prev: number[]) => (number | undefined)[]' is not assignable to type '(prevState: number[]) => number[]'.\n    Type '(number | undefined)[]' is not assignable to type 'number[]'.    
 
Type 'number | undefined' is not assignable to type 'number'.    
   
Type 'undefined' is not assignable to type 'number'.",
}]

Any help is appreciated.

4
  • can prev possibly be undefined? Commented Nov 8, 2022 at 22:36
  • Hello, do you have any reproducible code sample with your issue? Like code snippet, codesandbox? Commented Nov 8, 2022 at 22:36
  • how do you assign playerCount? Commented Nov 8, 2022 at 22:42
  • Change definition to setPlayerCounts?: React.Dispatch<React.SetStateAction<number[] | undefined>>; Commented Nov 8, 2022 at 23:03

1 Answer 1

2
setPlayerCounts(prev => [...(prev ?? []), playerCount!]);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank You! Can I ask what that bang(!) operator does at the end of playerCount? because that's what fixed the error
The (!) operator will force to no undefined type. ! is not null assertion operator.
Do take note that non-null assertion doesn't change the runtime behaviour, if playerCount is null or undefined during runtime and your code doesn't handle it, you might still run into problems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.