繁体   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