类型"{}"不可分配给类型“个人资料" [英] Type '{}' is not assignable to type 'Profile'

查看:90
本文介绍了类型"{}"不可分配给类型“个人资料"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是打字稿新手,并且收到错误消息

I'm new to typescript and im getting the error

类型"{}"不能分配给类型个人资料".

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

this.profile 上如何解决此问题?

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);
      })
    }
  }

推荐答案

您的问题是,您的 Profile 类型可能具有强制属性.您只需要使它们可选或将它们初始化为默认值即可.您不能将空对象分配给具有属性的类型.

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.

您也可以只说 profile:Profile 而无需初始化它.您仍在强制使用该类型.由于您只在订阅中分配它,因此您无需进行 {} 空对象分配.

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.

这篇关于类型"{}"不可分配给类型“个人资料"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆