vue.js Pinia $subscribe回调“mutation.payload”属性在PhpStorm中给出Typescript警告

osh3o9ms  于 2023-05-18  发布在  Vue.js
关注(0)|答案(1)|浏览(178)

我的代码实际上工作正常,但我收到了一个Typescript警告,说我不明白。

const dashboardStore = useDashboardStore()

dashboardStore.$subscribe((mutation) => {
  // This works OK!
  console.log(mutation.payload.id)
})

PhpStorm在mutation.payload上给了我一个警告:
TS2339:类型“SubscriptionCallbackMutation”上不存在属性“payload”。 属性“payload”不存在于
它正确地推断回调本身是一个Pinia SubscriptionCallback<DashboardState>
Pinia类型将mutation参数显示为SubscriptionCallbackMutation<S>类型,并声明该类型为:

export declare type SubscriptionCallbackMutation<S> = SubscriptionCallbackMutationDirect | SubscriptionCallbackMutationPatchObject<S> | SubscriptionCallbackMutationPatchFunction;

当然,类型SubscriptionCallbackMutationPatchObject具有我需要的patch属性。
所以如果我显式地键入回调参数...

dashboardStore.$subscribe((mutation: SubscriptionCallbackMutation<DashboardState>) => {
  // No errors or warnings
  const typedMutation = mutation as SubscriptionCallbackMutationPatchObject<DashboardState>
  console.log(mutation.payload.id)
}

但是我不能将mutation参数指定为SubscriptionCallbackMutationPatchObject<DashboardState>,这让我感到困惑。
有人知道为什么吗?我怎么能做到这一点,而不需要重新打字?

lxkprmvk

lxkprmvk1#

根据声明,我意识到Pinia的类型是明确的SubscriptionCallbackMutation<S>

export declare type SubscriptionCallbackMutation<S> = SubscriptionCallbackMutationDirect | SubscriptionCallbackMutationPatchObject<S> | SubscriptionCallbackMutationPatchFunction;

...但这并不能保证它是SubscriptionCallbackMutationPatchObject<S>,因此不会有payload属性。我来核实一下。
因此,我可以显式地键入mutation参数到SubscriptionCallbackMutation<DashboardState>,然后只签入方法调用,如下所示:

dashboardStore.$subscribe(async (mutation: SubscriptionCallbackMutation<DashboardState>) => {
  const params: DashboardQueryParams = {}
  if (mutation.type === MutationType.patchObject) {
    const payload = mutation.payload
    // Do stuff now that I know it's a Patch mutation.
  }
})

相关问题