Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows:

class Something {
    constructor(things) {
        if (things) {
            doSomething();
        } else return { errorCode: 1 }
    }
}

Does this code appear to be correct? When using TypeScript, I encounter an error message stating

property errorCode does not exist on type Something
. What could be a different method to handle this situation? Here is an alternative solution that comes to mind:

class Something {
    constructor(things) {
        if (things) {
            doSomething();
        } else this.error = { errorCode: 1 }
    }
}

Both options seem to achieve the same outcome. However, I am curious to understand which approach is more optimal.

Answer №1

Consider incorporating error handling within your class structure

interface CustomError {
  code: number;
}

class Example {
    private error: CustomError;
    constructor(items) {
        if (items) {
            performAction();
        } else this.error = { code: 1 };
    }
}

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 is the best way to transform tab navigation into a dropdown menu with the help

I have a collection of tabs currently on display. I am looking to transform them into a dropdown menu when the screen size changes, making them more responsive. Each set of tabs corresponds to different content. Despite trying various solutions found on s ...

Close button for body

I have created a form that floats in the center of the screen On this form, I have included a button designed to close it However, I would like for the form to be closed anywhere on the screen when clicked with the mouse Here is my code: $(".offer-clo ...

unable to utilize references in React

import React, { Component } from "react"; class Learning extends Component { firstName = React.createRef(); handleSubmit = event => { event.preventDefault(); console.log(this.firstName.current.value); } ...

Combining four numbers to calculate a total with the click of a button

I am currently attempting to calculate the sum of 4 entries in 4 separate text fields, and everything appears to be working correctly except that when I click the button, the sum is not being set. For example, if I enter the number 1 in each text input, th ...

How can I effectively send data from a view to a controller using AJAX in C# using Leaflet?

Every time I attempt to pass data from the view to the controller, I keep receiving an "alert request failed" message. I am uncertain of the datatype for leafletLats and leafletLngs, but they are both arrays derived from coord which is of type LatLng[]. ...

Is there a method in TypeScript to make an enum more dynamic by parameterizing it?

I've defined this enum in our codebase. enum EventDesc { EVENT1 = 'event 1', EVENT2 = 'event 2', EVENT3 = 'event 3' } The backend has EVENT1, EVENT2, EVENT3 as event types. On the UI, we display event 1, event 2, a ...

SailsJS failing to detect changes in local JSON file

https://i.stack.imgur.com/RG13Y.png This sailsjs application does not utilize any database. Instead, it relies on multiple JSON files located in the data folder within the root directory. The controller accesses this data as follows: req.session.categori ...

Issue encountered with websocket connection while attempting to include dependencies

My current project involves integrating charts for the graphical component using React within an Electron software. I've added interaction with buttons (sections) to insert different data into the graphs based on user clicks on one of the sections. Th ...

Exploring Elasticsearch: Uncovering search results in any scenario

I've been working on a project where my objective is to receive search engine results under all conditions. Even if I enter a keyword that is not included in the search data or if it is an empty string, I still want to get some kind of result. How can ...

Embrace the power of Angular2: Storing table information into

Custom table design Implement a TypeScript function to extract data from an array and populate it into a stylish table. ...

Preventing image flickering in SvelteKit: A guide

Upon the initial loading of a website, you may notice that the images tend to flicker or flash when transitioning between them. However, once these images are stored in the browser's cache, subsequent visits to the site will display the images seamles ...

Examining the execution of a function/method when a click event occurs within a functional component

It took me a while to realize that testing functional components with vue-test-utils can present some challenges In my case, I am utilizing Bootstrap-Vue's B-Button with a @click event that calls a function/method. When I attempt to test whether the ...

Vue.js: The href attribute in a link is different from the data

Having <a> href tag below, clicking will redirect to www.duckduckgo.com, with the value of page.publicWebsite being displayed as well. {{page.publicWebsite}} shows www.duckduckgo.com. Is everything functioning correctly? https://i.stack.imgur.com/ ...

Having trouble retrieving the .html() content from the <label> element

Check out the code below: $('.size_click').click(function () { $(this).closest('span').toggleClass('active_size'); $('.selected_sizes').append($(this).closest('label').html()); }); There are multiple ...

Tips for capturing audio in flac codec format using JS/AJAX

Is there a way to record audio in flac codec instead of opus codec? I attempted setting the codec to flac like this: let blob = new Blob(audioChunks,{type: 'audio/ogg; codecs=flac' }); I also tried this: var options = { audioBitsPerSecond : ...

Unable to fetch source for HTML img tag

I am struggling with using jQuery to retrieve the src attribute of an image when it is clicked. Unfortunately, my current code does not output anything to the console and returns undefined when I try to manipulate it in the browser console. I do not have m ...

What steps should I take to plan a collaborative code-sharing project?

As I develop various applications utilizing a core framework of my own creation, I am looking for a way to easily manage updates across all these applications. I have structured the code by creating a GitHub project where the main branch consists of the co ...

Windows authentication login only appears in Chrome after opening the developer tools

My current issue involves a React app that needs to authenticate against a windows auth server. To achieve this, I'm hitting an endpoint to fetch user details with the credentials included in the header. As per my understanding, this should trigger th ...

JavaScript problem with setting values in 2D array

I am attempting to assign values to a 2d array at particular indices. During each iteration, all sub-arrays at the j index are being assigned the same variable (number). inputTensor dimensions: 140x7 - 140 arrays of size 7 inputMinArray dimensions: 1x7 - ...

Execute a function when a selection option is chosen consecutively two times

I have a dynamic dropdown menu that uses AJAX to load options. I need the function to be triggered not only when an option is changed, but also when the same option is clicked multiple times in a row. In other words, I want the function to run every time a ...