tips for converting 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 a certain method, I want to achieve something similar to this

let teacher = Utilisateur.getUilisateurConnecter();

then I would like to invoke a function from Enseignant like this

teacher.add( new ... ) ; However, it gives an error: property 'add' does not exist on type 'Utilisateur' usually in java you can cast like : Animal n = new Dog() I was considering doing something like this : let teacher : Enseignant = Utilisateur.getUtilisateurConnecter()

Answer №1

It all boils down to one question - do you truly know if your User is an Instructor? If so, you can simply cast it like this:

let instructor = user as Instructor;

But keep in mind that TypeScript doesn't perform runtime checks like Java does. So, if your user turns out to be a Student instead of an Instructor, your code will continue running until it encounters an issue when trying to access properties specific to an Instructor.

If unsure about the type of your User, use instanceof for validation since Instructor is a class (if it were just an interface, validation would differ):

if (user instanceof Instructor) {
    let instructor = user; // confirmed as an Instructor
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What methods can TypeScript use to accommodate this kind of Generic Type?

It appears that there is already an existing GitHub issue related to this topic. You can find it here: ts#1213. This type of usage resembles a high-order function, and I am unsure if TypeScript supports it. Although the interface remains the same, there ...

Using NodeJS to facilitate communication between multiple NodeJS instances while also overseeing operations of a Minecraft server

I have a question about communicating between NodeJS instances. Let's say I have one NodeJS instance running a chat room - how can I access that chat and see who is connected from another NodeJS instance? Additionally, I'm curious if it's f ...

Traversing a nested array using jQuery

I'm attempting to utilize jQuery's each function in order to iterate through the provided array. My aim is to identify the key ("Name") and display its corresponding array values on the webpage. Array ( [E-mail] => Array ( ...

I am unable to produce sound by clicking on the drum machine

My goal is to develop a basic react drum machine project that I discovered on freecodecamp. The objective is to display 9 drumpads and trigger sound upon clicking. Update: I have successfully rendered all the keys but I am facing issues with the function ...

The _.get function is not compatible with the module.exports object

After exporting an object from a node file, my code is not functioning as expected. (path './../../config/cloud.js): module.exports = { some: { property: 1 } } Even though I am using the following code: const config = require(&ap ...

Eliminating repetitions in Angular JS ng-options / ng-repeat

I currently have the following data stored in my JavaScript: $scope.jsonmarkers = [{ "name": "Jeff", "type": "Organisation + Training Entity", "userID": "1" }, { "name": "Fred", "type": "Organisation + Training Entity", ...

Adjust the cursor in a contenteditable division on Chrome or Webkit

Is there a way to set the caret position in a contenteditable div layer? After trying different methods and doing some research online, I finally found a solution that works in firefox: function set(element,position){ element.focus(); var range= w ...

PHP website freezes unexpectedly in Firefox version 4

For over a year, our website has been functioning perfectly. However, with the release of Firefox4, we have noticed a new issue. Occasionally, the page hangs randomly. I have tested the website on IE8/9, Chrome10+, Safari, and Opera, and the issue only see ...

React doesn't properly display JSON data

I am facing an issue with the code below that is supposed to display data from a JSON file. Instead of showing the desired data, it only displays the h1 with curly braces. Here is the faulty code: import prod from "../../data/produtos.json"; exp ...

What is the best way to eliminate all occurrences of a specific element within an array?

I'm currently facing an issue with my code - it's supposed to remove all instances of a certain item from an array, but it's not working as expected. Can anyone help me identify what I'm doing wrong? let nums = [1, 90, 90, 1123, 90, ...

Executing a Python script within an ASP.NET application upon loading

I have a python script that scrapes a webpage for currency conversion. I successfully used this script in a previous php project and now need to adapt it for use in asp.net. In the past, I executed the python script using JavaScript by loading it on the h ...

Retrieve the chosen date from a DatePicker using a Javascript function

Is there a way to retrieve the user-selected date using a JS function? I attempted this method: var test = $("#datepicker").datepicker( 'getDate' ); However, when I display it with an alert, it shows [object object] instead of the date. This ...

PHP JSON object requires a solution for successful Ajax requests

I've been working on creating a user search system similar to Facebook using AJAX and PHP JSON. However, I've encountered a problem. In the users table data, there are entries for Marc Zuckerberg, Marc Zeyn, and Marc Alp. Essentially, there are ...

Encountering an issue with Angular 12: The error message "TypeError: teardown.unsubscribe is

Since updating my app to Angular 12, I've been encountering an unusual error message every time I move away from a component that has ngOnDestroy function with .unsubscribe() calls. What's even more peculiar is that the teardown.unsubscribe menti ...

Adding pointlights to the camera in three.js is a great way to

I have written some code to add two lights on the camera that move along with the orbitcontrols. However, the lights and spheres are not visible for some reason. Can someone help me identify the issue in my code? var sphere1 = new THREE.Mesh( new THREE.Sp ...

Utilizing Google Closure Library with Angular 6

I am looking to integrate the google closure library into my angular 6 application. To achieve this, I have utilized the following commands: npm install google-closure-compiler and npm install google-closure-library. My application can be successfully co ...

Executing prototype functions after a function has been defined

I'm looking to expand my knowledge on JavaScript prototypes. I came across some NodeJS modules where functions were being called in a chain like this: something.funcA().funcB().funcC(); and I want to implement something similar. How can I achieve this ...

Can anyone help me with fixing the error message 'Cannot assign to read-only property 'exports' of the object' in React?

Recently, I decided to delve into the world of React and started building a simple app from scratch. However, I have run into an issue that is throwing the following error: Uncaught TypeError: Cannot assign to read-only property 'exports' of o ...

Is there a way to transfer a variable from Angular 2 Frontend Express JS to an Angular 2 component?

After conducting thorough research, I have made specific modifications to my code. However, I am encountering some errors in my console that I cannot seem to resolve. Despite following a tutorial step by step. Your assistance would be highly valued as I a ...

Is there a method to track the progress of webpage loading?

I am working on a website built with static HTML pages. My goal is to implement a full-screen loading status complete with a progress bar that indicates the page's load progress, including all images and external assets. Once the page has fully loaded ...