簡體   English   中英

Typescript 初始化為空 object

[英]Typescript initialize empty object

我正在了解 typescript,我正在努力處理下面的這段代碼。

      const profile = state.currentProfile;
      type literalProfile = keyof Partial<Omit<Profile, 'id'>>;

      const values: Record<literalProfile, string | undefined> = {
        name: '',
        avatar: '',
        title: '',
        subtitle: '',
      };

      Object.entries(data).forEach((entry) => {
        const key = entry[0] as literalProfile;
        const value = entry[1];
        if (value && profile[key] !== value) {
          values[key] = value;
        }
      });

      await this.$axios.patch(`/users/profiles/${profile.id}`, values);

問題是,有沒有辦法像這樣將值初始化為空的 object?

const values: Record<literalProfile, string | undefined> = {};

因為如果我做這樣的事情 typescript 突出顯示錯誤

類型“{}”缺少類型“Record<"name" | 中的以下屬性 “標題” | “副標題” | “頭像”,字符串 | undefined>':名稱、標題、副標題、頭像

如果我嘗試這樣的事情

let values: Record<literalProfile, string | undefined>;

然后 typescript 說

在分配之前使用變量“值”。

在這一行

await this.$axios.patch(`/users/profiles/${profile.id}`, values);

所以我不知道如何解決這個問題,有什么想法嗎?

目前,您正在使用Record<listeralProfile, string | undefined> Record<listeralProfile, string | undefined>

相反,您應該使用{ [key in literalProfile]?: string }

有細微差別。 兩者都支持undefined作為值,但是通過使用可選的字段關鍵字? 您可以在初始化 object 時省略這些字段。

const values: { [key in literalProfile]?: string } = {};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM