K
K
Konstantin2018-07-16 17:45:54
typescript
Konstantin, 2018-07-16 17:45:54

How to specify the type of an object?

I have a variable defined like this:
public headerUser: IHeaderStaff | IHeaderPupil;
Where interfaces are declared:

export interface IHeaderPupil {
  photo: string;
  fullname: string;
  school: string;
  class: string;
  formmaster: string;
  schools: string;
}

export interface IHeaderStaff {
  photo: string;
  fullname: string;
  school: string;
}

There is also a factory that returns an object of one or another interface:
public static getFactory(profile: ProfileBase, i18nService: I18nService): IHeaderPupil | IHeaderStaff {

    if (profile instanceof PrincipalProfile) {
      return {
        'photo': profile.getPhoto(),
        'fullname': profile.getName(true),
        'school': profile.getOrganizationName(Helper.currentLanguage(i18nService)),
        'schools': profile.getName()
      };
    } else if (profile instanceof PupilProfile) {
      return {
        'photo': profile.getPhoto(),
        'fullname': profile.getName(true),
        'school': profile.getOrganizationName(Helper.currentLanguage(i18nService)),
        'class': profile.getName(),
        'formmaster': profile.getName(),
        'schools': profile.getName()
      };
    } else if (profile instanceof StaffProfile) {
      return {
        'photo': profile.getPhoto(),
        'fullname': profile.getName(true),
        'school': profile.getOrganizationName(Helper.currentLanguage(i18nService))
      };
    }

    return null;
  }

The problem is that when using the factory, I don’t know exactly what type is returned, and when I try to access the property, an error occurs:
public headerUser: IHeaderStaff | IHeaderPupil;
this.headerUser = this.userService.header();

If you access the class property of the this.headerUser object, an error will occur.
It is possible not to specify the return type as: any , but not yet an option

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question