What is the proper way to refactor this TypeScript class?

Can you assist me in converting this class into TypeScript and explaining why it's not functioning?

class Students {
    public name: string;
    public surname: string;
    public age: number;
}
constructor(name:string,surname:string,age:number) {
    this.name = name;
    this.surname = surname;
    this.age = age;
}
public updateStudentInfo(name:string, surname:string,age:number):void {
    this.name = typeof name !== 'undefined' ? name : this.name;
    this.surname = typeof surname !== 'undefined' ? surname : this.surname;
    this.age = typeof age !== 'undefined' ? age : this.age;
}
public studentInfoToString():object{} {
    return `\nName: ${this.name}, Surname: ${this.surname} Age: ${this.age}`
}
let student1 = new Students("Aladin","Indus", 20);
console.log(student1.studentInfoToString());

Answer №1

After analyzing the details provided, it appears that this is the solution you are seeking.

export class Students {

    public name: string;
    public surname: string;
    public age: number;

    constructor(name: string, surname: string, age: number) {
        this.name = name;
        this.surname = surname;
        this.age = age;

        let student1 = new Students("Aladin", "Indus", 20);
        console.log(student1.toString());
    }

    public refactorStudent(name: string, surname: string, age: number): void {

        this.name = typeof name !== 'undefined' ? name : this.name;
        this.surname = typeof surname !== 'undefined' ? surname : this.surname;
        this.age = typeof age !== 'undefined' ? age : this.age;
    }

    public toString(): string {
        return `\nName: ${this.name}, Surname: ${this.surname} Age: ${this.age}`;
    }
}

I trust this provides the assistance you were looking for.

Answer №2

Initialization of public fields can be automated within the constructor. It is highly likely that instead of refactorStudent, it would be more efficient to directly assign values to the public attributes. If necessary, you can add get and set methods for these attributes for protection in the future.

export class Student {
    constructor(public name: string, public surname: string, public age: number) {}

    public toString(): string {
        return `\nName: ${this.name}, Surname: ${this.surname} Age: ${this.age}`;
    }
}

let student1 = new Student("Aladin", "Indus", 20);
console.log(student1.toString());

The reason your original code did not function correctly was due to the placement of the constructor and methods outside the class definition.

Additionally, the class itself should be named Student since each instance represents a single student. For classes representing a collection of objects, use singular form for names unless it pertains to multiple instances (e.g. a classroom full of them).

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

While running tslint in an angular unit test, an error was encountered stating 'unused expression, expected an assignment or function call'

Is there a method to resolve this issue without needing to insert an ignore directive in the file? Error encountered during command execution: ./node_modules/tslint/bin/tslint -p src/tsconfig.json --type-check src/app/app.component.spec.ts [21, 5]: unuse ...

Converting a file buffer to upload to Google Cloud Storage

I have been facing an issue while attempting to upload a file to Google Cloud using a buffer and the save function. The problem I am encountering is that even though the files are uploaded to Google Cloud, they are not in the correct format. When I try to ...

Error encountered while attempting to utilize 'load' in the fetch function of a layer

I've been exploring ways to implement some pre-update logic for a layer, and I believe the fetch method within the layer's props could be the key. Initially, my aim is to understand the default behavior before incorporating custom logic, but I&ap ...

Displaying user input data in a separate component post form submission within Angular

I recently developed an employee center app with both form and details views. After submitting the form, the data entered should be displayed in the details view. To facilitate this data transfer, I created an EmployeeService to connect the form and detail ...

Having trouble extracting parameters with TypeScript in React Router even when they are present

I am in the process of migrating an older project to utilize react and react-router. Additionally, I am fairly new to typescript, which is the language used for this particular project. Any guidance or explanations on these topics would be highly beneficia ...

What is the best way to choose checkboxes from data that is passed dynamically?

https://i.stack.imgur.com/L3k59.png I am looking to add an edit feature to my application. When the user clicks on the edit option, they should be taken to a different page with the previously entered value displayed. While I have successfully retrieved ...

Utilizing the Next.js "Link" Element as a Personalized React Component Using Typescript

When attempting to utilize the "Link" element as a custom react component that I modified with typescript to enhance its functionality, I encountered a recurring issue in my project. Each time I used it, I had to include a property named props which contai ...

Changing the value of an element in an array using typescript within an Angular context

I am currently working with Angular 5 and I have a task to update the array values based on the selectedMobile array. Below is my code snippet: const mobilelist = [ { 'key': 'apple', 'name': 'Apple', 'check ...

It seems that an error has occurred: DOMException was thrown because the attempt to run 'importScripts' on 'WorkerGlobalScope' has failed. The script located at 'http://localhost:4200/BlinkCardWasmSDK.js' was unable to load properly

Recently, I attempted to integrate this credit card reader into my Angular application. Despite carefully following all the installation steps and obtaining a valid license key, I encountered the following error: Error during the initialization of the SDK! ...

What steps should I take to resolve the issue of "Error: The pipe 'filter' could not be located! Error: The pipe 'filter' could not be found!" in Angular version 10?

I am encountering an issue with a filter that is supposed to search for a specific name and retrieve the data containing that name. However, I am only seeing an error in the browser console, and the page is not displaying as expected. Here is the HTML cod ...

Is it possible to pass a prop from a parent container to children without knowing their identities?

I am currently working on a collapsible container component that can be reused for different sections of a form to display fields or a summary. Each container would include a Form object passed as a child. Here is the basic structure of my code: function C ...

What is the process for defining the type or interface of an object in Visual Studio Code?

Is there a way to create a new type or interface by replicating the structure of a complex object that is imported from a library? For instance, in the image below, the object Text is taken from react-three/drei. https://i.sstatic.net/BcUzd.png Upon inspe ...

Issue encountered while authenticating client secret from backend for newly created Stripe subscription

There seems to be an issue with confirming the client secret sent from the express backend to the frontend, specifically in a React Native-based mobile application. The clientSecret is being sent in the same manner as described above. On the frontend Rea ...

Executing functions on React components with no render method

Currently, I am in need of a component that will handle app settings. This particular component, named Settings, utilizes the useState() hook to store state values such as the primary color scheme. I aim to have a single instance of this Settings componen ...

RouteConfig not found in Vue3 Router when using Typescript

After initializing a new Vue project using @vue/cli $> vue create my-project, I opted for Typescript and router options, then updated to vue3 beta using $>vue add vue-next. Unfortunately, when running $>npm run serve, I encountered the following ...

Fixing the error message stating 'Argument of type '{}' is not assignable to parameter of type 'any[]'. [ng] Property 'length' is missing in type '{}'. Here are steps to resolve this issue:

Currently, I am in the process of developing an Ionic Inventory Management application that incorporates a Barcode Scanner and SQLite database by following this tutorial: Upon adding the following code snippet: async createTables(){ try { awa ...

Can a Typescript class type be defined without explicitly creating a JavaScript class?

I am exploring the idea of creating a specific class type for classes that possess certain properties. For example: class Cat { name = 'cat'; } class Dog { name = 'dog'; } type Animal = ???; function foo(AnimalClass: Animal) { ...

When working with a union type in TypeScript, it is important to note that the property may

Imagine a scenario where I am dealing with two specific interfaces: interface Box { x: number y: number } and interface ColouredBox { x: number y: number colour: string } For the sake of this discussion, let's assume that the ...

What is the process for turning off a TypeScript rule for a single line of code?

Dealing with Summernote as a jQuery plugin has been a bit of a struggle for me. I'm trying to modify the object without needing type definitions, but TypeScript keeps throwing errors my way. Even after attempting to delete certain keys, I still get th ...

Having trouble with ng-select focus in Angular 5?

I've been attempting to implement focus on ng-select within Angular 5, but unfortunately, it doesn't seem to be working as expected. Currently, I am utilizing ng2-select for my project. Is there a specific method for implementing focus on ng-se ...