代码之家  ›  专栏  ›  技术社区  ›  TinyTiger

当使用Pinia和TypeScript时,如何使用动作来设置状态?

  •  0
  • TinyTiger  · 技术社区  · 4 年前

    我有一家名为Pinia+TypeScript的商店 user.ts 看起来是这样的:

    import { User } from 'firebase/auth';
    import { defineStore } from 'pinia';
    export const useUserStore = defineStore('user', {
      state: () =>
        ({
          displayName: null,
          email: null,
          emailVerified: null,
          isAnonymous: null,
          metadata: null,
          multiFactor: null,
          phoneNumber: null,
          photoURL: null,
          providerData: null,
          providerId: null,
          refreshToken: null,
          tenantId: null,
          uid: null,
        } as unknown as User),
      actions: {
        setPhotoURL(photoURLData: string | null) {
          this.photoURL = photoURLData; //<-- ERROR HERE
        },
      },
    });
    

    状态是FireBase用户对象。

    我想更新一下 photoURL 使用 setPhotoURL() 行动

    但是 照片网址 有以下类型脚本错误:

    Cannot assign to 'photoURL' because it is a read-only property. ts(2540)
    

    我做错了什么?

    这是更新状态的正确方法吗?

    1 回复  |  直到 4 年前
        1
  •  1
  •   tao    4 年前

    'firebase/auth' 声明用户界面具有 readonly 道具。当您将该接口强制应用于状态对象时,TS信任您。

    把它摊开,应该可以去除 只读 从它的道具,同时仍然推断出类型:

    export const useUserStore = defineStore('user', {
      state: () => ({ ...({
        displayName: null,
        email: null,
        emailVerified: null,
        isAnonymous: null,
        metadata: null,
        multiFactor: null,
        phoneNumber: null,
        photoURL: null,
        providerData: null,
        providerId: null,
        refreshToken: null,
        tenantId: null,
        uid: null,
      } as unknown as User) }),
      actions: {
        //...
      }
    })
    
    推荐文章