如何在打字稿中投射对象

时间:2021-02-20 00:59:38

标签: javascript typescript casting

import { Enseignant } from "./Enseignant";
import { AlreadyExistsError } from "./errors/AlreadyExistsError";
import { Etudiant } from "./Etudiant";

export class Utilisateur {
  private _id: string;
  private _first_name: string;
  private _last_name: string;
  private _email: string;
  private _token: string;

  private static user: Utilisateur;

  constructor(id: string, first_name: string, last_name: string, email: string, token: string) {
     this._id = id;
     this._first_name = first_name;
     this._last_name = last_name;
     this._email = email;
     this._token = token;
   }

  public static connectUser(id: string, first_name: string, last_name: string, email: string, token: string): Utilisateur {
    if (Utilisateur.user) {
      throw new AlreadyExistsError("Un utilisateur est deja connecte");
    } else {
      if(email.includes("teacher")) {
        Utilisateur.user  = new Enseignant(id, first_name, last_name, email, token);//TODO ajouter tout les params de Enseignant
      } else {
        // Utilisateur.user = new Etudiant(id, first_name, last_name, email, token, code_permanant );//TODO ajouter tout les params de Etudiant
      }
      // Utilisateur.user = new Utilisateur(id, first_name, last_name, email, token);
    }

    return Utilisateur.user;
  }

  public static getUtilisateurConnecte(): Utilisateur {
    return Utilisateur.user;
  }

  public getId() {
    return Utilisateur.user._id;
  }

  public getFirstName() {
    return Utilisateur.user._first_name;
  }

};

import { Cours } from "./Cours";
import { NotFoundError } from "./errors/NotFoundError";
import { Utilisateur } from "./Utilisateur";

export class Enseignant extends Utilisateur {
    private _idEnseignant : string;
    private _mapCours : Map<string,Cours>;
    private _cours : Cours;

    

    constructor(idEnseignant:string, prenom:string, nom:string, email:string, token:string) {
        super(idEnseignant, prenom, nom, email, token);
        this._mapCours = new Map<string,Cours>();
        
    }

    public set setCours(cours: Cours){
        this._cours = cours;
    }
    public add(cours: Cours){
        this.mapCours.set(cours.sigle, cours)
    }

    public getCours(){
        return this._cours;
    }

   
    // moi
    public get Cours(){
        return this._cours;
    }

    public ajouterEtudiant(id:string, prenom:string, nom:string, email:string, codePermanent:string, sigle:string){
        let cours = this.getCoursSpecifique(sigle);
        cours.ajouterEtudiant(id,prenom,nom,email,codePermanent)
    }


    public get mapCours() {
        return this._mapCours;
    }

    public getCoursSpecifique(sigle:string){
        return this._mapCours.get(sigle);
    }

    

    /**
     * Utile pour : CU01b -demanderDetailsCours
     * Méthode permettant d'obtenir les informations du cours
     * Les informations sont le sigle, le titre, les détails 
     * du cours ainsi que la liste des codes permanents de tous 
     * les étudiants incrits dans un groupe cours associé à ce 
     * cours
     * @param sigle Le sigle du cours
     */
    public getInfosCours(sigle:string) {
        let cours = this._mapCours.get(sigle);

        if (cours === undefined) {
            // Le cours n'existe pas
            throw new NotFoundError("Cours '" + sigle + "'n'existe pas.");
        }

        let resultat = {
            messageSigle: "Sigle du cours : ",
            sigle: sigle,
            messageTitre: "Titre du cours : ",
            titre: cours.titre,
            messageDetails: "Détails du cours : ",
            detail: cours.detail
            //messageCP: "Code permenanents des étudiants inscrits : "
            //codePermanents: cours.getEtudiantsCours(),
        };
        
        return resultat; 
     
    }
   

    public toJSON() {
        return {
            "idEnseignant": this._idEnseignant,
        }
    }
}

在某些方法中,我试图做这样的事情

让老师 = Utilisateur.getUilisateurConnecter();

那么我想像这样从 Enseignant 调用一个函数

teacher.add(new ...); 但它说:“Utilisateur”类型上不存在“add”属性 通常在java中你可以像这样:Animal n = new Dog() 我正在考虑做这样的事情: 让老师:Enseignant = Utilisateur.getUtilisateurConnecter()

1 个答案:

答案 0 :(得分:1)

那要看情况。如果您知道您的 Utilisateur 实际上是一个 Enseignant,您可以使用:

let enseignant = utilisateur as Enseignant;

然而,值得注意的是,与 Java 不同的是,TypeScript 不会在运行时验证此转换是否正确,因此如果您的 utilisateur 恰好是 Etudiant,您的代码将继续,并且只有在需要特定于 Enseignant 的属性但未找到时才会失败。

如果你不确定 Utilisateur 是什么类型,你可以使用 instanceof 来检查,因为 Enseignant 是一个类(如果它只是一个接口,你d 需要以不同的方式检查类型):

if (utilisateur instanceof Enseignant) {
    let enseignant = utilisateur; // is known to be of type Enseignant
}
相关问题