Defining Objects in TypeScript

Within my TypeScript application, I currently have the following code:

interface Data {
    url: string,
    // more stuff
}

(...)

export class something() {
    public data: Data;
}

method(){
    this.data.url = "things";
}

However, every time I attempt to assign a value to data.url, I encounter an error stating that I cannot set the property url of undefined. What mistake am I making here? And what is causing this issue?

Thank you in advance!

Answer №1

1) The correct syntax for a class declaration should be:

export class something { 
}

and NOT

export class something() { 
}

2) method is declared outside of the class, it should be inside the class

3) this.data is currently undefined and you're trying to access the url property of an undefined variable, resulting in an error.

interface Data {
    url: string,
    // more details
}

(...)

export class something {
    public data: Data;
    method(){
        this.data = {
           url: "something",
           // more details
        }
    }
}

If you need to access method from outside the class, make sure to instantiate the class something.

method() {
    let obj = new something();
    obj.data = {
        url: "something",
        // more details
    }
}

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 correct way to implement a validation pattern in Angular2 to prevent users from entering only spaces in an

I am using formBuilder in Angular2 and need to implement a validation pattern to prevent input that consists of only spaces. ...

The element within the iterator is lacking a "key" prop, as indicated by the linter error message in a React component

Encountering an error stating Missing "key" prop for element in iteratoreslintreact/jsx-key {[...Array(10)].map((_) => ( <Skeleton variant="rectangular" sx={{ my: 4, mx: 1 }} /> ))} An attempt to resolve this issue was made ...

Comprehending the concept of TypeScript type assertion

Currently, I'm learning TypeScript and I came across a code snippet that is causing some confusion. var str = '1' var str2:number = <number> <any> str //str is now of type number console.log(typeof(str2)) log: String From m ...

The error you are seeing is a result of your application code and not generated by Cypress

I attempted to test the following simple code snippet: type Website = string; it('loads examples', () => { const website: Website = 'https://www.ebay.com/'; cy.visit(website); cy.get('input[type="text"]').type(& ...

create a fresh variable instead of appending it to the current object

I'm encountering an issue where a new array is supposed to be added on callback using props, but instead an empty variable is being added. Here's the code snippet: const [data, setData] = useState({ title: "", serviceId: "", serviceNa ...

Uploading Files within Angular FormArray

I am facing an issue with my formArray which contains file upload inputs in each element. Whenever I upload an image in one input, it changes the values of other file inputs in different rows. https://i.stack.imgur.com/3haZW.png Current Behavior: Uploadi ...

Using typescript with create-react-app - organizing types in a separate file

I'm currently developing a project using Create React App with TypeScript (create-react-app myapp --typescript) In my App.tsx file, I have written some TypeScript code that I want to move to an external file. I have tried creating App.d.ts, index.d.t ...

What is the best way to create a function that shifts a musical note up or down by one semitone?

Currently developing a guitar tuning tool and facing some hurdles. Striving to create a function that can take a musical note, an octave, and a direction (up or down), then produce a transposed note by a half step based on the traditional piano layout (i. ...

Which objects can be looped through in Aurelia templating?

In the documentation for Aurelia, it mentions that repeaters can be used with arrays and other iterable data types, including objects, as well as new ES6 standards like Map and Set. Map is usually recommended, as shown in the example below: <template&g ...

Retrieve the :id parameter from the URL as a numerical value in Node.js using Typescript

Is there a way to directly get the :id param from the URL as a number instead of a string in order to easily pass it on to TypeORM for fetching data based on a specific ID? Currently, I am using the following approach where I have to create an additional ...

Get a list of images by incorporating NextJs and Strapi to create a dynamic slider feature

[] I need help creating a slider as I am encountering an error when trying to output an array of objects. The error can be seen here: . Can someone assist me in resolving this issue? Thank you. Here is a screenshot from the admin panel: 1 Below is the c ...

When the button onClick event is not functioning as expected in NextJS with TypeScript

After creating a login page with a button to sign in and hit an API, I encountered an issue where clicking the button does not trigger any action. I have checked the console log and no errors or responses are showing up. Could there be a mistake in my code ...

Here's a unique version: "Utilizing the onChange event of a MaterialUI Select type TextField to invoke a function."

I am currently working on creating a Select type JTextField using the MaterialUI package. I want to make sure that when the onChange event is triggered, it calls a specific function. To achieve this, I have developed a component called Select, which is es ...

What is the best way to add query parameters to router.push without cluttering the URL?

In my current project, I am using NextJS 13 with TypeScript but not utilizing the app router. I am facing an issue while trying to pass data over router.push to a dynamically routed page in Next.js without compromising the clarity of the URL. router.push({ ...

Error: The Select2 query service is not available

I am looking to enhance the search functionality for my select2 dropdown. My goal is to trigger a service call with the search parameters once 3 characters are typed into the search field. However, when I try to select an option from the dropdown, I encou ...

Encountering a Typescript error while trying to implement a custom palette color with the Chip component in Material-UI

I have created a unique theme where I included my own custom colors in the palette. I was expecting the color prop to work with a custom color. I tested it with the Button component and it performed as expected. However, when I attempted the same with the ...

What methods can TypeScript employ to comprehend this situation?

There's an interesting scenario when it comes to assigning a variable of type unknown to another variable. TypeScript requires us to perform type checking on the unknown variable, but how does TypeScript handle this specific situation? It appears that ...

Issue with ToggleButtonGroup causing React MUI Collapse to malfunction

I'm having trouble implementing a MUI ToggleButtonGroup with Collapse in React. Initially, it displays correctly, but when I try to hide it by selecting the hide option, nothing happens. Does anyone have any suggestions on what might be causing this ...

Prevent Duplicate Service Instances in Angular

After doing some thorough research online, I've identified the root of my issue: multiple instances of a particular service are being created. I need assistance in pinpointing and rectifying this problem within my code. The secondary service is depen ...

Assign an appropriate label to this sonarqube input field

Sonarqube flagged an issue with the following line of code: <div class="dropdown-language"> <label>{{'GENERALE.LINGUA' | translate }}</label> <select #langSelect (change)="translate.use(langSe ...