Issue with constructor including an interface

I'm facing an issue with a typescript class that has an interface implemented in the constructor parameter:

    interface responseObject {
      a: string;
      b: boolean;
      c?: boolean; 
   }

   class x
   {
     a: string;
     b: boolean;
     c: boolean; 
     constructor(args: responseObject) {
       //checking if non-optional parameters are not supplied
       if(!args.a || !args.b) throw new Error("Error"); 
       //Attempting to initialize class data member -> but it's not working
       this.a = args.a;
       this.b = args.b;
     }
   }

Now, I have two questions. My first question is how can I access the different parameters supplied inside args. For example, how could I check if they are both supplied (similar to what I tried with !args.a or !args.b). And my second question is how can I provide a default value for c if it is not supplied?

Thank you in advance.

Answer №1

It is possible to accomplish that task.

constructor({ x, y, z = 'defaultValue' }) {
    //validate if required parameters are not provided
    if(!x || !y) throw new Error("Error"); 
}

Keep in mind that you must specifically throw the error as there isn't a shorthand syntax for it.

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

The feature for favoriting or unfavorite a post is currently not functioning correctly on the frontend (react) side

I have been working on a social media website project for practice, and I successfully implemented the liking and disliking posts feature. However, I encountered an issue where when I like a post and the icon changes to a filled icon, upon refreshing the p ...

`Integrate Passport Azure AD authentication into your GraphQL Server's Context`

Seeking assistance from experienced individuals to tackle some async JavaScript issues. I am trying to secure a GraphQL server using the Passport library and the passport-azure-ad strategy. The validation of incoming Access Tokens seems to be working fine ...

Get rid of the TypeScript error in the specified function

I am currently working on implementing a "Clear" button for a select element that will reset the value to its default state. Here is a snippet of my code: const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => { onChange( ...

Sending an Ajax request to a nearby address

I'm feeling a bit lost on how to achieve this task. I've been searching online, but it seems like my search terms may not have been quite right. My goal is to set up a RESTful api. $.ajax({ type: "POST", url: "https//my.url/", data: ...

What steps should I take to resolve issues with the npm installation on Linux?

I'm encountering an issue while attempting to use npm install in order to install a package. Despite my attempts to update and re-download from the root directory, I am unable to resolve the error. hackathonday1-2 git:(save-button) ✗ npm install f ...

ES6: Using DataURI to provide input results in undefined output

In my current project, I am facing a challenge. I am attempting to pass image dataURI as an input from a url link to the image. To achieve this task, I know that I have to utilize canvas and convert it from there. However, since this process involves an &a ...

An issue has occurred while trying to execute the npm start command within PhpStorm

When I try to run npm start on Windows' command prompt, it works fine. However, I encounter errors when running it in the PhpStorm Terminal. You can see the errors here. Is this a result of them being different platforms or could it be related to som ...

What is the best way to adjust a map to completely fill the screen?

I am experiencing an issue with my Openlayer map not fitting to full screen automatically. Despite trying various settings, I am unable to resolve this issue. Can anyone suggest what might be causing this problem? Thank you in advance https://i.stack.imgu ...

Iterate over the contents within the div tag

I need help with looping through the data in this specific div container. My goal is to extract row by row data from it. <div id="result" runat=server> <div id="gvResult" class="RowGroup"> <div class="Row RowBg" tabindex="99"> ...

Retrieving JSON data using the fetch method in JavaScript

Currently, I am attempting to retrieve a JSON array using AJAX. Upon calling my test.php file, the following content is returned: [{"name":"James","age":24},{"name":"Peter","age":30}] This is the JavaScript code that I am using: var persons = new Array( ...

Creating dynamic elements in JavaScript and assigning them unique IDs

Hi there, I'm currently working on a project that requires generating dynamic divs with a textbox and delete button inside each one. The challenge I'm facing is figuring out how to assign a unique ID to each textbox element so that I can properly ...

What is the method of posting to PHP using JavaScript without utilizing Ajax?

My current code involves a drag and drop file uploader to PHP using ajax, but it seems that my web host does not support ajax. Is there an alternative method to achieve this without using ajax? Specifically, I am facing issues with the UploadFile functio ...

Error Styling: Using CSS to Highlight Invalid Checkboxes within a Group

Is there a way to create a bordered red box around checkboxes that are required but not selected? Here is the code I currently have: <div class="fb-checkbox-group form-group field-checkbox-group-1500575975893"> <label for="checkbox-group-15005 ...

Struggling to combine select dropdown choices in one calculation

​​I'm currently working on a project where I need to create a website that multiplies three numbers selected from dropdown menus together. However, when I attempt to perform the calculation, I only get the result "1" displayed. I've spent sev ...

Can angular and grunt support multiple run blocks simultaneously?

Currently, I am configuring $httpBackend to simulate fake API routes while our team of API developers is building them out. However, I am facing an issue where I have to place all the $httpBackend configurations within my run block. This leads to a situa ...

Typescript throws an error indicating that the "this" object in Vue methods may be undefined, displaying error code TS2532

As a beginner in question writing, I apologize if my wording is not clear. The issue at hand: I am working on a Vue application with TypeScript. export default { methods: { setProgram: (program: Program)=>{ this.program = progra ...

How can you assign a unique number to each item within the same category in order to differentiate them?

const productData = [ {size: 1180160, category: "Keswick", index: 1}, {size: 1059328, category: "HCOPA", index: 2}, {size: 30720, category: "HCOPA", index: 3}, {size: 493056, category: "Darhan Saluja", index: 4}, {size: 267776, category: "CRSA", index ...

Customize the CSS for material-ui buttons or create a new style altogether

Looking to customize the background color of a material UI RaisedButton, I have encountered a challenge. This is what I currently have: const style = { backgroundColor: 'green' }; export default class CreateLinksave extends React.Component { ...

Tips on positioning a div based on the screen dimensions

In my table, there is an icon that reveals a chart as a popup when hovered over. This div is where the chart is displayed: <div id="chart-outer" style="@style" class="popup-chart close"> <h2 id="charttitle&q ...

What is the best way to retrieve a value from an array?

Using ASP.net Core, I receive information from my API. In Angular, the data looks like this: 0: {Id: 3, Role_Name: 'ITAdmin'} 1: {Id: 4, Role_Name: 'Admin'} 2: {Id: 5, Role_Name: 'user'} I want to extract values from this arr ...