【问题标题】:how to cast an object in typescript如何在打字稿中投射对象
【发布时间】:2021-02-20 00:59:38
【问题描述】:

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()

【问题讨论】:

  • Utilisateur.getUilisateurConnecter 是否返回 UtilisateurEnseignant。这里不说类型,它实际上返回什么?
  • 另外请减少您的代码示例。 90% 不是必需的,我们不需要查看您的实际代码,只需演示该想法的最小版本即可。

标签: javascript typescript casting


【解决方案1】:

这取决于。如果你知道你的Utilisateur 实际上是一个Enseignant,你可以使用:

let enseignant = utilisateur as Enseignant;

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

如果您不确定Utilisateur 是什么类型,您可以使用instanceof 进行检查,因为Enseignant 是一个类(如果它只是一个接口,您需要检查类型不同):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2019-04-11
    • 1970-01-01
    • 2018-06-18
    • 2022-12-23
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多