Typescript Omit属性与’as’关键字不起作用

huangapple go评论74阅读模式
英文:

Typescript Omit property not working with 'as' keyword

问题

在注册时需要这两个属性,但在此之后密码将不再需要。
想法是,系统将使用Firebase内置函数进行注册和身份验证,但系统的其他所有内容都将存储在Firebase用户集合中。

我的问题是,当我有两种类型的用户(一种用于注册,一种通用类型)时:

export interface RegistrationUser extends firebase.UserInfo {
  email: string;
  password: string;
}

export type User = Omit<RegistrationUser, 'password'>;

registerUser(user: RegistrationUser) {
    this.auth.createUserWithEmailAndPassword(user.email, user.password).then(() => {
      let newUser = user as User;
      // 将用户属性保存到Firebase用户集合中
      this.collection.add(newUser);
    });
}

尽管使用了 'as' 关键字,但 password 属性仍然被保存。
如何设置不将密码保存到用户集合中?

谢谢。

英文:

During registration both property need but after it password won't need.
The idea is, for registration and authencation the system will use firebase built in functions, but everything else system will store in firebase user collection.

My problem is, when i have two type of user (one for registration, one general type):

export interface RegistrationUser extends firebase.UserInfo {
  email: string;
  password: string;
}

export type User = Omit&lt;RegistrationUser, &#39;password&#39;&gt;;

registerUser(user: RegistrationUser) {
    this.auth.createUserWithEmailAndPassword(user.email, user.password).then(()=&gt; {
      let newUser = user as User;
      // save user prop to firebase user collection
      this.collection.add(newUser);
    });
}

Despite of 'as' keyword, the password property still saved.
How can I set to not save the password to user collection?

Thanks

答案1

得分: 3

Typescript在像这样做一些事情时实际上并不会删除属性。这只是为了静态分析类型的目的(Typescript在运行时不存在)。要真正删除属性,你需要像这样做:

const newUser: User = {email: user.email};
英文:

Typescript don't really remove the property when you do something like this. It is just for static analysis type purposes (Typescript does not exists on runtime). To really remove the property you need to do something like this:

const newUser: User = {email: user.email};

huangapple
  • 本文由 发表于 2020年1月3日 20:58:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定