Type '{}' is not assignable to type 'Profile'

删除回忆录丶 提交于 2019-12-11 17:36:53

问题


I'm new to typescript and im getting the error

Type '{}' is not assignable to type 'Profile'.

on this.profile how can I fix this?

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFirestore } from 'angularfire2/firestore';
import { Profile } from './../../models/profile';


@IonicPage()
@Component({
  selector: 'page-profile',
  templateUrl: 'profile.html',
})
export class ProfilePage {

    profile = {} as Profile;

    constructor(private afs: AngularFirestore, private afAuth: AngularFireAuth,
      public navCtrl: NavController, public navParams: NavParams) {
    }
    ionViewWillLoad() {
      this.afAuth.authState.take(1).subscribe(data => {
          let profileCollection = this.afs.collection('profiles').doc(`${data.uid}`).valueChanges();
          profileCollection.subscribe(profile => this.profile = profile);
      })
    }
  }

回答1:


Your problem here is that probably your Profile type has mandatory properties. You just have to either make them optional or initialize them to default values. You can’t assign an empty object to a type with properties.

What you can do is also just say profile: Profile without initialising it. You’re still enforcing the type. Since you are only assigning it inside the subscribe you don’t need to do the {} empty object assignment.




回答2:


Type '{}' is not assignable to type 'Profile'.

If you want to use an assertion like that you need to use the double assertion pattern i.e.

profile = {} as any as Profile;

More

  • Search double assertion typescript
  • I wrote about it as well : https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html


来源:https://stackoverflow.com/questions/48392672/type-is-not-assignable-to-type-profile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!