简体   繁体   English

Typescript 初始化为空 object

[英]Typescript initialize empty object

I'm learning about typescript, and I'm struggling with this code below.我正在了解 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);

The question is, Is there any way to initialize values as an empty object, like this?问题是,有没有办法像这样将值初始化为空的 object?

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

Because if I do something like this typescript highlight me an error因为如果我做这样的事情 typescript 突出显示错误

Type '{}' is missing the following properties from type 'Record<"name" |类型“{}”缺少类型“Record<"name" | 中的以下属性"title" | “标题” | "subtitle" | “副标题” | "avatar", string | “头像”,字符串 | undefined>': name, title, subtitle, avatar undefined>':名称、标题、副标题、头像

If I try something like this如果我尝试这样的事情

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

Then typescript says然后 typescript 说

Variable 'values' is used before being assigned.在分配之前使用变量“值”。

In this line在这一行

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

So I don't know how to fix that, any ideas?所以我不知道如何解决这个问题,有什么想法吗?

Currently, you're using Record<listeralProfile, string | undefined>目前,您正在使用Record<listeralProfile, string | undefined> Record<listeralProfile, string | undefined> . Record<listeralProfile, string | undefined>

Instead, you should use { [key in literalProfile]?: string } .相反,您应该使用{ [key in literalProfile]?: string }

There's a subtle difference.有细微差别。 Both support undefined as a value, but by using the optional field keyword ?两者都支持undefined作为值,但是通过使用可选的字段关键字? you can omit those fields when initializing your object.您可以在初始化 object 时省略这些字段。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM