In TypeScript, what is the appropriate type for the parameter "data" in a Class constructor?

Here is the code I'm working with:

export class People {
    name: string;
    age: number;
    constructor(data: any) {
        this.name = data.name;
        this.age = data.age;
    }
}

I keep encountering an error when using 'any'. What should be the appropriate type for data to avoid any errors?

I am aware that I can also write it as:

export class People {
    name: string;
    age: number;
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}

However, I want this model to be able to handle any JSON object, like one retrieved from a server, so that I can do:

const data = await fetchData();
const person = new Person(data)

What modifications should I make in order to continue using the model for any object and eliminate all TypeScript errors?

I attempted changing the type to: object, but then encountered errors on data.name and data.age

Answer №1

If you want to learn more about interfaces, check out this LINK

Your code will then look something like this:

interface PersonData {
    name: string;
    age: number;
}

export class People {
    name: string;
    age: number;
    constructor(data: PersonData) {
        this.name = data.name;
        this.age = data.age;
    }
}

Answer №2

If you're looking to establish a similar structure, consider implementing the following:

interface IUser {
  username: string;
  email: string;
}

export class User {
    username!: string;
    email!: string;

    constructor(details: IUser) {
        Object.assign(this, details);
    }
}

For a more type-safe approach, you can destructure the properties in the constructor:

export class User {
    username: string;
    email: string;

    constructor({ username, email }: IUser) {
        this.username = username;
        this.email = email;
    }
}

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

Switching to a different URL path in JavaScript by adjusting the parent directory

Here's the situation: http://domain/request.php?id=123 On this website, there is a button with a submit handler that should redirect to http://domain/submit_solution#/?id=123 Attempted solution: $('#r_submit_form').click(funct ...

Determine the selected radio button

----EDIT---- I am developing a jQuery mobile application and I need to determine which radio button is selected. This is the JavaScript code I'm using: function filter(){ if(document.getElementById('segment1').checked) { aler ...

What is the best way to handle apostrophes in individuals' names in PHP and JavaScript?

I've encountered an issue where certain name entries, such as O'Rourke or O'reilly, can break JavaScript in some cases. I'm curious about how others handle this situation. Do you typically replace these names before inserting them into ...

JavaScripts loaded dynamically

Currently in the process of developing an Ajax-powered web application with JQuery that permits users to open the same page multiple times within one area. However, this setup often leads to conflicts related to the DOM and "unique ids". To address this i ...

Foreground and background color pairs extraction tool for parsers

When analyzing a static webpage where the only source of colors is in either the CSS files or HTML file itself, how can we extract foreground-background color pairs from the page? For instance, on the Google home page, some potential color pairs could be ( ...

The functionality to rename a label by clicking on an image button is currently malfunctioning

There seems to be an issue with this code where the label name is not changing as expected when clicking the image button. I have noticed that upon closer inspection, the label does change momentarily but then reverts back to its original value immediatel ...

Encountering a RangeError when transmitting OpenLayers3 event via AJAX

An error is appearing in the chrome console stating: RangeError: Maximum call stack size exceeded The code I am using is as follows: draw.on('drawend', function(evt) { var fe = evt.feature console.log(fe); ...

PHP error: User data failed to be transmitted

I'm currently working on a website for capturing still photos of students. However, I'm facing an issue when trying to transfer the collected data and upload the picture with the corresponding "ID" provided in the prompt. For some reason, the dat ...

What is the purpose of using the http module to specify the port when the app.listen function already sets the

var express = require("express"); var app = express(); // This code sets the port to 8080 by default, or else it will use the environment-specific port. app.set('port', process.env.PORT || 8080); app.get('/', function(req, res){ r ...

Angular : Is toFixed() functioning properly with one value but not with the other one?

My form has 2 inputs, each calling the calculeSalaire() function. calculeSalaire() { this.fraisGestion = this.getFraisGestion(); this.tauxFraisGestion = this.getTauxFraisGestion(); this.salaireBrut = this.getSalaireBrut(); this.salaireNet = this.g ...

What is the best way to display every single column from the datasource in an Angular material table?

Currently, I am attempting to create an Angular material mat-table using the resources provided in the official documentation found at this link. The table I am working on consists of approximately 10 columns. Is there a way to dynamically display all the ...

A method for highlighting duplicate rows in a DataTable by formatting them with the same color

I am currently utilizing the DataTable plugin to display rows in a table. I would like to highlight duplicate rows in the same color scheme. Can someone please assist me with this issue? In the example below, the entry for Black Winters is duplicated. I ai ...

What is the significance of using interfaces in parentheses when assigning typescript types?

These are the 2 interfaces I currently have export interface Contact { first_name: string; last_name: string; emails?: (EmailsEntity)[] | null; company: string; job_title: string; } export interface EmailsEntity { email: string; label: strin ...

Retrieving JSON Data using Fetch

My JSON file consists of a simple object containing 2 arrays: { "key1": ["a", "b", "c"], "key2": [ "d", "e", "f"] } When using JavaScript, I fetch the data and push it into an array to use it. const jsonData = '/things.json'; const myArray = ...

How does Vue handle the situation when the value of an input field does not match the bound "data"?

Before diving into the intricacies of v-model, I want to take a closer look at how v-bind behaves. Let's analyze the example below: <div id="app"> <input type="text" :value="inputtedValue" @input ...

Enable Ace Editor's read-only mode

I'm having some difficulty getting my ace-editor to work in read-only mode. I'm working with Angular 9 and I've attempted the following approach: In my HTML file, I have the following code: <ace-editor mode="java" theme="m ...

The module 'Express' does not have a public member named 'SessionData' available for export

I am encountering an issue while working on my TypeScript project. I am not sure where the error is originating from, especially since nothing has been changed since the last time I worked on it. node_modules/connect-mongo/src/types.d.ts:113:66 - error TS ...

Is the current version of Bootstrap experiencing issues with Data-bs-toggle functionality?

I have encountered an issue where the bootstrap 5.1.3 data-bs-toggle feature is no longer functioning properly. For example: <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" datadat-b ...

The placeholder within my input moves up and down when switching the input type from password to text

Currently, I am encountering an issue with the styling of a standard input element in React. Specifically, the placeholder text moves up and down by about 2px when viewed on Chrome, while there are no problems on Safari. How can I go about resolving this i ...

What is the best way to add a CSS style to any element that has the .btn:hover pseudo-class, except for those elements with the class '.dropdown-toggle'?

Is there a way to apply a style to all my .btn elements when hovering, except for those with the .dropdown-toggle class? I've tried a couple of methods but ran into some issues: attempt 1: .btn:not(.dropdown-toggle):hover { background-color: inher ...