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

97 Views Asked by At

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'.

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?

1

There are 1 best solutions below

0
Nicholas Tower On BEST ANSWER
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);