TypeScript 错误ts2322 Type 'Dispatch<SetStateAction<undefined>>' is not assignable to type 'Dispatch<SetStateAction<MyType | undefined>>'
问题描述
我在编写 useState()
的包装器时遇到了一个我不理解的错误:
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'.
这是我的代码:
const useStateIAPSubscription = (): [
CdvPurchase.VerifiedPurchase | undefined,
React.Dispatch<
React.SetStateAction<CdvPurchase.VerifiedPurchase | undefined>
>,
] => {
const [subscription, setSubscription] = useState(undefined);
return [subscription, setSubscription];
};
export default useStateIAPSubscription;
我试图创建一个默认值为undefined的useState()钩子。我希望setState()函数只接受undefined或特定类型(CdvPurchase.VerifiedPurchase)。
我这样做的原因是应用程序在订阅准备好之前初始化,我希望稍后通过useState()添加它。
如何修复这个TypeScript错误?
解决方案
const [subscription, setSubscription] = useState(undefined);
由于您没有指定此状态包含的数据类型,TypeScript会尽力推断它。它看到初始值为 undefined
所以它假设状态是(且始终为) undefined
。
由于您希望它能够更改为非undefined值,您需要提供一个明确的类型,如下所示:
const [subscription, setSubscription] = useState<CdvPurchase.VerifiedPurchase | undefined>(undefined);