如何添加对象属性以满足Typescript中的类类型?

肖恩

按照下面的“内部码localRegister ”功能,我增加了“用户id ”和“ ACCOUNTTYPE ”到createUserObj使用括号符号,所以它能够满足的属性对象用户类类型。

但我仍然收到该消息,指出 User 缺少 userId、accountType 属性。

似乎是一个我无法弄清楚的简单问题......我们如何让 Typescript 理解这些属性已经被添加,或者是否有另一种正确的方法来添加属性?

提前致谢。

user.service.ts(部分代码)

  async localRegister(createUserDto: LocalUserDto) {
    const passwordHash = await bcrypt.hash(createUserDto.password, 10);
    let createUserObj = { ...createUserDto, password: passwordHash };

    createUserObj['userId'] = uuid();
    createUserObj['accountType'] = 'local';

    this.userCreate(createUserObj);  // <====== typescript error here
       //   Argument of type '{ password: string; username: string; email: string; }' is not assignable to parameter of type 'User'.
       //   Type '{ password: string; username: string; email: string; }' is missing the following properties from type 'User': userId, accountType
  }

  async userCreate(userObj: User) {
    const createdUser = new this.userModel(userObj);
    try {
      await createdUser.save();
    } catch (err) {
      throw new NotFoundException(err.message);
    }
  }

user.schema.ts(定义用户类型的地方)

@Schema()
export class User {
  @Prop({ required: true })
  userId: string;

  @Prop({ required: true })
  username: string;

  @Prop({ unique: true })
  email: string;

  password: string;

  @Prop({ required: true })
  accountType: string;
}

TJ克劳德

我希望 TypeScript 会抱怨用字符串索引该对象。但无论如何,如果您使用方括号表示法,我认为 TypeScript 不会因为您使用字符串而扩大类型。

您可以从一开始就使用所有属性构建对象:

async localRegister(createUserDto: LocalUserDto) {
    const passwordHash = await bcrypt.hash(createUserDto.password, 10);
    const createUserObj = {
        ...createUserDto,
        password: passwordHash,
        userId: uuid(),                // ***
        accountType: 'local',          // ***
    };

    this.userCreate(createUserObj);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章