简体   繁体   English

如何在 typescript 中投射 object

[英]how to cast an object in typescript

 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, } } }

in some method, im trying to do something like this在某种程度上,我试图做这样的事情

let teacher = Utilisateur.getUilisateurConnecter();让老师 = Utilisateur.getUilisateurConnecter();

then I would like to call a function from Enseignant like this然后我想像这样从 Enseignant 调用 function

teacher.add( new... );老师。添加(新...); But it says: property 'add' does not exist on type 'Utilisateur' normally in java you can cast like: Animal n = new Dog() I was thinking about doing something like this: let teacher: Enseignant = Utilisateur.getUtilisateurConnecter()但它说:属性 'add' 通常在 java 中的类型 'Utilisateur' 上不存在,你可以这样转换: Animal n = new Dog() 我正在考虑做这样的事情:让老师:Enseignant = Utilisateur.getUtilisateurConnecter()

That depends.那要看。 If you know your Utilisateur is actually an Enseignant , you can use:如果您知道您的Utilisateur实际上是Enseignant ,则可以使用:

let enseignant = utilisateur as Enseignant;

However, it is worth noting that unlike Java, TypeScript will not verify at runtime that this cast is actually correct, so if your utilisateur happens to be an Etudiant instead, your code will proceed, and only fail much later when a property specific to Enseignant is required but not found.但是,值得注意的是,与 Java 不同,TypeScript 不会在运行时验证此转换实际上是否正确,因此如果您的utilisateur恰好是Etudiant ,您的代码将继续运行,并且仅在Enseignant特定的属性时失败很久是必需的,但没有找到。

If you don't know for sure what kind of Utilisateur it is, you can use instanceof to check since Enseignant is a class (if it were a mere interface you'd need to check the type differently):如果您不确定它是哪种Utilisateur ,您可以使用instanceof进行检查,因为Enseignant是 class (如果它只是一个接口,您需要以不同的方式检查类型):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM