Yet another method for transferring arguments in typescript

I have a TypeScript class with a method that takes three arguments.

class MyClass {

 public static carStatus(name : string , color : string , isReady : boolean){
    let result = isReady ? 'is ready' : 'is not ready';
    return `${color} ${name} ${result}.`;
 }
}

let carStatus = MyClass.carStatus('pride' , 'white' , true);
console.log(carStatus);

I am looking to modify the way the third argument (isReady) is passed into the method by moving it outside of the brackets.

class MyClass {

public static isReady : boolean;

  public static carStatus(name : string , color : string){
    let result = this.isReady ? 'is ready' : 'is not ready';
    return `${color} ${name} ${result}.`;
  }
}

MyClass.isReady = false;
let carStatus = MyClass.carStatus('pride' , 'white');
console.log(carStatus);

Are there any other methods to achieve the same outcome?

Answer №1

In my opinion, a straightforward approach would involve creating a dedicated method to define the isReady status and employing a singular CarStatus class without static methods:

class CarStatus {
    private isReady: boolean;

    constructor(private name: string, private color: string) {
        this.name = name;
        this.color = color;
    }

    public setReady() {
        this.isReady = true;
    }

    public getStatus(): string {
        let result = this.isReady ? 'is ready' : 'is not ready';
        return `${this.color} ${name} ${result}.`;
    }
}

let carStatus = new CarStatus("pride", "white");
carStatus.setReady();
console.log(carStatus.getStatus());

If deemed necessary, an alternative fluent approach could be considered where individual attributes can be set at different times. However, using this method may be excessive in some situations. Here's an illustration:

class CarStatus {  
    constructor(private name: string, private color: string, private isReady: boolean) {
        this.name = name;
        this.color = color;
        this.isReady = isReady;
    }

    public getStatus(): string {
        let result = this.isReady ? 'is ready' : 'is not ready';
        return `${this.color} ${name} ${result}.`;
    }
}

class CarStatusBuilder {
    private name: string;
    private color: string;
    private isReady: boolean;

    public SetReady(): CarStatusBuilder {
        return new CarStatusBuilder() { this.isReady = true};
    }

    public WithName(name: string): CarStatusBuilder {
        this.name = name;
        return this;
    }

    public WithColor(color: string): CarStatusBuilder {
        this.color = color;
        return this;
    }

    public Build(): CarStatus{
        return new CarStatus(this.name, this.color, this.isReady);
    }
}

let carStatus = new CarStatusBuilder()
    .WithColor("white")
    .WithName("pride")
    .Build();
console.log(carStatus.getStatus());

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

Unable to generate a file using fs.appendFile in Node.js

For some time now, I've been working on a program that is meant to save logs from a Slack team. I've managed to get most things working, but I've hit a roadblock with using fs.appendFile() successfully. The documentation states that it shoul ...

Using jQuery to implement interactive hover effects on individual items within a list

I'm currently developing a project that involves displaying speech bubbles next to each list item when hovered over. These speech bubbles contain relevant information specific to the item being hovered on. To achieve this functionality, I've crea ...

Show just three items simultaneously

I am currently working on a quote generator and I want to add a feature that allows me to display a specific number of quotes at a time. I attempted to use map for this purpose, but encountered an error stating it's not a function. Currently, the gene ...

Is it necessary to include async/await in a method if there is already an await keyword where it is invoked?

Here are the two methods I have written in Typescript: async getCertURL(pol: string): Promise<string> { return await Api.getData(this.apiUrl + pol + this.certEndpoint, {timeout: 60000}).then( (response) => { return response.data.certUR ...

Creating a number of arrays based on the row of a .CSV file can be accomplished in Angular by utilizing the

Implementing an Angular template to read .CSV files and generate a table involves creating two separate files: one for the header and another for the table content. For the header CSV file: header.csv https://i.stack.imgur.com/ojMo6.png For the table da ...

Trouble with shadow rendering in imported obj through Three.js

After importing an object from blender and setting every mesh to cast and receive shadows, I noticed that the rendered shadows are incorrect. Even after merging the meshes thinking it would solve the issue, the problem persisted. It seems like using side: ...

Ways to implement StackNavigator along with Redux?

Is there anyone who can assist me in integrating StackNavigator and Redux? It seems straightforward, but I'm encountering issues. index.ios.js import React from 'react' import { AppRegistry } from 'react-native' import { Provi ...

json data hidden from sight in jQuery

Snippet of HTML Code: <select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);"> <option value="">--Select--</option> <option value="Value11">Value1</option> <option value="Value2">Value2</op ...

How to prioritize indices when querying multiple indexes in Elasticsearch?

Utilizing the Elasticsearch multi index API, I am able to query across multiple indices. However, it is important for me to prioritize my queries. As an illustration, when querying in the indices index1 and index2, the syntax would look like: /index1,ind ...

Utilizing Angular 4: Sharing Data through Services and Components

After transitioning my data from an object in a service to a database connection, I'm facing issues where the data is not reaching the component as expected. To solve this problem, I have set up the service to subscribe to the data retrieved from the ...

Guide on creating a detailed list of categories mapped to specific classes that all adhere to a common generic standard

Most TypeScript factory patterns I've encountered rely on a named mapping between a name and the Class type. A basic implementation example: const myMap = { classOne: ExampleClass, classTwo: AnotherClass } (k: string) => { return new myMap[k] } ...

Using Vuetify to filter items in a v-data-table upon clicking a button

My table structure is similar to this, https://i.sstatic.net/56TUi.png I am looking to implement a functionality where clicking on the Filter Button will filter out all items that are both male and valid with a value of true. users = [ { name: &apos ...

The call to 'setRequestHeader' on 'XMLHttpRequest' was unsuccessful due to the object's state not being OPENED

While developing an angular application with a restful API get(), I encountered a few errors such as unauthorization error:401 which I managed to resolve. However, now I am facing another error that seems quite straightforward. I even tried adding the CORS ...

Vue - Unable to navigate to a different route

I just started working with Vue and attempted to redirect '/home' to '/travel', but for some reason it's not functioning correctly. Can someone please guide me on how to achieve this? What could be the issue with my code? Thank y ...

Discovering the Firefox Add-on Bar's Height utilizing Javascript

Did you know that Firefox's Addon toolbar can vary in size depending on whether text is displayed along with icons? Is it feasible to determine the exact height using javascript? ...

Accessing a variable from another HTML using JavaScript

I'm currently attempting to access a variable from another HTML file using JS. Specifically, I have a file (file1.htm) that opens a dialog box, and I want to send the information of the selected file to another file (file2.htm) in order to modify a v ...

Searching for paired values within an array using Javascript or Jquery

In my JavaScript code, I am working with an array called ppts that looks like: var ppts = []; //... ppts.push({x: mouse.x, y: mouse.y}); //... var tmpArr = []; for (var i=1;ppts.length-1; i++) tmpArr.push(ppts[i].x); alert(tmpArr[2]); tmp_ctx.lineTo(pars ...

Manipulating webpage content with JavaScript

How can I provide visual feedback to a user while an ajax request is in progress? For example, when a user clicks a 'process' button that triggers an AJAX request to a server-side script, they should see a 'loading...' message and a gra ...

Vuetify offers a convenient solution for implementing multiple buttons in a Vue

My search bar retrieves data from an API query in the following format: Data: [[id, datafield1, datafield2],[id, datafield1, datafield2],...] I wish to include an on/off button for each row of the data, with each button having its own independent state. ...

Always keep your phone in landscape orientation for optimal website viewing

Currently, I am facing an issue with my website where it functions perfectly on mobile devices in landscape orientation but elements get distorted when viewed in portrait mode. Is there a method to ensure that the website is always displayed in landscape ...