Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ts2322 Type 'Dispatch<SetStateAction<undefined>>' is not assignable to type 'Dispatch<SetStateAction<MyType | undefined>>'

I’m having trouble writing a wrapper for useState() because I’m getting an error I don’t understand:

Type ‘Dispatch<SetStateAction>’ is not assignable to type
‘Dispatch<SetStateAction<VerifiedPurchase | undefined>>’.

Type ‘SetStateAction<VerifiedPurchase | undefined>’ is not assignable to
type ‘SetStateAction’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type ‘VerifiedPurchase’ is not assignable to type ‘SetStateAction’.

Type ‘VerifiedPurchase’ provides no match for the signature ‘(prevState: undefined): undefined’.

Here’s my code:

const useStateIAPSubscription = (): [
  CdvPurchase.VerifiedPurchase | undefined,
  React.Dispatch<
    React.SetStateAction<CdvPurchase.VerifiedPurchase | undefined>
  >,
] => {
  const [subscription, setSubscription] = useState(undefined);
  return [subscription, setSubscription];
};

export default useStateIAPSubscription;

What I’m trying to do is to create a useState() hook with a default value of undefined. I want the setState() function to only accept undefined or a specific type (CdvPurchase.VerifiedPurchase).

I’m trying to do it this way because the app is initialized before the subscription is ready, and I want to add it later with useState().

How can I fix this TypeScript error?

>Solution :

const [subscription, setSubscription] = useState(undefined);

Since you haven’t specified what type of data this state will contain, typescript does its best to infer it. It sees that the initial value is undefined so it assumes the state is (and always will be) undefined.

Since you want it to be able to change to a non-undefined value, you’ll need to provide an explicit type, as in:

const [subscription, setSubscription] = useState<CdvPurchase.VerifiedPurchase | undefined>(undefined);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading