Creating a new object in Typescript and populating it with default values based on a class

What is the best way to design a TypeScript class or JavaScript object that initializes with default properties? I am currently using TypeScript classes with parameters as shown below:

Here is an example of my class:

export class StateModel {
  stateID: number;
  stateCode: string;
  stateName: string;
  stateTwoCharCode: string;

  constructor(
    stateId: number, 
    stateCode: string = '', 
    stateName: string = '',
    stateTwoCharCode: string = ''){
    this.stateID = stateId;
    this.stateCode = stateCode;
    this.stateName = stateName;
    this.stateTwoCharCode = stateTwoCharCode;
  }
}

When importing and using this class, I would like to be able to do something similar to:

let newClass = new StateModel();

If I were to log newClass, I expect to see the following result:

newClass = {
  stateCode: '',
  stateName: '',
  stateTwoCharCode: ''
}

However, I would prefer for the constructor parameters to be optional. Is there a way to achieve this?

Answer №1

Utilize optional parameters in your script. The only essential element that seems to be missing is the private keyboard:

export class StateModel {
  stateID: number;
  stateCode: string;
  stateName: string;
  stateTwoCharCode: string;

  constructor(
    stateId: number, 
    private stateCode: string = '', 
    private stateName: string = '',
    private stateTwoCharCode: string = ''){
    this.stateID = stateId;
    this.stateCode = stateCode;
    this.stateName = stateName;
    this.stateTwoCharCode = stateTwoCharCode;
  }
}

Answer №2

Your implementation of the optional parameter is functioning properly. To initialize it, simply use the following syntax:

exampleVariable: ExampleType = new ExampleType(1);

Answer №3

Link to TypeScript example

When converted to TypeScript, the following code snippet is created:

export class StateModel {
  constructor(
    public stateId: number, 
    public stateCode: string = '', 
    private stateName: string = '',
    private stateTwoCharCode: string = ''){

  }
}

const foo = new StateModel(123)
console.log(foo,"foo")

This TypeScript code transpiles to JavaScript as shown below:

export class StateModel {
    constructor(stateId, stateCode = '', stateName = '', stateTwoCharCode = '') {
        this.stateId = stateId;
        this.stateCode = stateCode;
        this.stateName = stateName;
        this.stateTwoCharCode = stateTwoCharCode;
    }
}
const foo = new StateModel(123);

Upon logging foo, you can observe the intended object structure.

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

Error in React JS: TypeError - Attempting to extend a class with an undefined value, which is not a

I am new to React and experimenting with a code example on https://jscomplete.com/repl. Currently, my code appears as follows: let data = [ { name:"Paul O’Shannessy", avatar_url:"https://avatars1.githubusercontent.com/u/8445?v=4", c ...

How to filter dependency-injected asynchronous data based on conditions?

I have developed a NodeJS application that utilizes dependency injection. One of the key features of the app is that it can execute multiple functions (modules) simultaneously, and if multiple modules request data from the same async resource, the app ensu ...

How to retrieve JSON data from unidentified objects using JQuery

I have made an AJAX call and received a JSON file as the response: [ { "LINKNAME": "Annual Training", "HITS": 1 }, { "LINKNAME": "In Focus Newsletter", "HITS": 1 }, { "LINKNAME": "NITA (secured)" ...

Calculating the number of duplicate elements in an array

I need help with displaying the elements of an array while also counting duplicates. For example: myArr = ['apple', 'apple', 'orange', 'apple', 'banana', 'orange', 'pineapple'] The out ...

Utilizing jQuery Ajax to submit multiple forms using a single selector in one go

I'm having an issue with jQuery Ajax involving multiple forms. Each time I execute it, only the top form works properly while the others do not function as expected. Can anyone provide assistance with this? Here is the source code: <form id="form_ ...

The active class in the Bootstrap carousel is not updating when trying to change

I am struggling to make the Twitter Bootstrap carousel function properly. Although the slides automatically change after the default timeout, the indicators do not switch the active class, resulting in my carousel failing to transition between slides. Ini ...

There appears to be an issue with Three.js as it is indicating that the node.apply

I am currently attempting to import a .fbx file using the FBXLoader from three.js with the following code block: var fbxLoader = new THREE.FBXLoader(); fbxLoader.load('assets/item2.fbx', function (object){ object.position.y = -100; scene.add(obj ...

Creating Input Fields on the Fly in VueJS

My goal is to dynamically manipulate input fields in real-time. I found a helpful solution at , which successfully adds and removes fields as needed. However, when attempting to save the input values to the database, the functionality breaks. Here is the ...

Steps for accessing the files uploaded in a React application

Looking to implement an upload button using material UI that allows users to upload multiple files, with the goal of saving their paths into an array for future use. However, I'm unsure about where these uploaded files are stored. The code snippet be ...

Having trouble retrieving json data from PHP page using jQuery $.ajax

Having trouble accessing this JSON data in JavaScript, as when I try to alert it the result comes back as undefined Below is the jQuery code snippet: $.ajax({ type: "POST", url: "frmMktHelpGridd.php", data: { labNo: secondElement ...

Successive type label

Looking to create an object that can have either primitives or objects as properties? Avoid pitfalls like the following: const obj: DesiredType = { correctProp1: 'string', correctProp2: 123, correctProp3: true, wrongProp4: [1, 2, 3], pr ...

Implementing easy-fit in an AngularJS application without the need for requirejs

I am currently exploring the use of an interesting JavaScript library called easy-fit (https://github.com/pierremtb/easy-fit) within an AngularJS application (https://github.com/khertan/forrunners). Easy-fit relies on gulp and babel. My goal is to transpi ...

Why is Node.js unable to locate my files?

I'm currently utilizing Node.js as my server, and I'm encountering some difficulties in serving my JS and CSS files. For some reason, index.html is unable to locate them. Whenever I try to load up my browser, I encounter the following error: htt ...

How can you include a comma between two objects within a string, excluding the last object, using JavaScript?

I have a string object stored in a variable passed from another class. My question is how can I add a comma between two objects, excluding the last object? Below is my code snippet: { "id":"57e4d12e53a5a", "body":"asdas", "publishe ...

Understanding the functionality of imports within modules imported into Angular

I have been scouring through the documentation trying to understand the functionality of the import statement in JavaScript, specifically within the Angular framework. While I grasp the basic concept that it imports modules from other files containing expo ...

Mastering typing properties in React with TypeScript

Could someone please help me with this issue? I have created a basic react component. interface iRowData{ name: string } export default function ResultsSection(data: iRowData[]) { return <div>Results</div> } When I try to use it in ano ...

Receiving undefined when subscribing data to an observable in Angular

Currently, I am facing an issue in my Angular project where subscribing the data to an observable is returning undefined. I have a service method in place that retrieves data from an HTTP request. public fetchData(): Observable<Data[]> { const url = ...

useEffect issue: unable to use map function with API data in React Hooks

I am facing an issue where the code below is not populating the UL with any items except for the "Default LI" that I manually added. Despite having data in response.data and all console.log calls showing output, the items are not being populated. I suspect ...

retrieving data from a separate div and injecting it into the current page using an ajax request

I have a script that calls the HTML of a div from another page to display on the current page. Here is the code snippet: <script> $(document).ready(function($)) { $('#add').click( function() { $. ...

Differences between a readonly variable and a method with a readonly type in TypeScript

Exploring the Contrast Between Readonly Variables and Readonly-Typed Methods in TypeScript Readonly Variable: maxLength: Readonly<Number | number | String | string> = 1; vs Readonly-Typed Method: maxLength(length: Number | number | String | stri ...