Is there a way to retrieve a data type from a class in TypeScript?

Within my code, there exists a class:

class Person {
   name: string;
   age: number;
   gender: string;

   constructor(params: any){
     this.name = params.name;
     this.age = params.age;
     this.gender = params.gender;
   }
}

My question is how can I extract a type from the class Person that mirrors the following structure:

 type PersonType = {
   name: string;
   age: number;
   gender: string;
 }

I want to avoid redundancy when defining the type by manually writing it out. Is there a way to automatically generate the type based on the class definition?

I wish to avoid duplicating the following code snippet:

   name: string;
   age: number;
   gender: string;

Answer №1

Simply specify the class as type

Enjoy the Playground experience

class Person {
  name: string;
  age: number;
  gender: string;

  constructor(params: Person) {
    this.name = params.name;
    this.age = params.age;
    this.gender = params.gender;

    this.gender = params.gender2; // issue here
  }
}

const test1 = new Person({ age: 1, gender: '1', name: '1' });
const test2 = new Person({ age: 1, gender: '1' }); // problem occurs

You also have the option to utilize Object.assign for initializing all fields at once, but remember to provide a default value for each field

class Person {
  name: string = "default";
  age: number = 0;
  gender: string = "default";

  constructor(params: Person) {
    Object.assign(this, params);
  }
}

const test3 = new Person({ age: 1, gender: '1', name: '1' });
const test4 = new Person({ age: 1, gender: '1' }); // an issue may occur

Answer №2

I'm uncertain if I understand you correctly.

However, could this be what you're looking for?

class Individual {
   name: string;
   age: number;
   gender: string;

   constructor(details: Individual){
     this.name = details.name;
     this.age = details.age;
     this.gender = details.gender;
   }

  someFunction?: () => void = () => {};
}

Example of how to Use

const individual: Individual = new Individual(...);

https://i.stack.imgur.com/ooQwY.png

Answer №3

Utilize classes for defining types, such as:

class A { name: string; };
let foo: A = { name: "John" };

But considering your input, perhaps explicitly defining constructor parameters could be more straightforward?

export class Person {
   name: string;
   age: number;
   gender: string;

   constructor(name: string, age: number, gender: string){
     this.name = name;
     this.age = age;
     this.gender = gender;
   }
}

What do you think of this approach?

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

Validating React Typescript Props: Ensuring that two specific props do not exist simultaneously

Currently, I'm developing a reusable component in React-Typescript and I am looking to validate my props OnClick and component as follows: Both onClick and component prop are optional. These props will only be passed to the component if they need to ...

The use of React hooks in an application saga led to an issue where, despite using history.push, the component

Thank you for checking out this question. I have created a login demo using react hooks and TypeScript. I have some concerns: 1. When the login is successful, I use history.push('/home') to navigate to the home page, but the page also renders a N ...

Converting JSON to TypeScript in an Angular project

Within my Angular project, I have an HTTP service that communicates with a web API to retrieve JSON data. However, there is a discrepancy in the naming convention between the key in the JSON response (e.g., "Property" in uppercase) and the corresponding pr ...

The Radio Button's value appears in a distinct way on Ionic Angular

I am currently working with the Ionic framework and I am trying to display data values on radio buttons. However, I am facing difficulties in retrieving the correct value and setting it appropriately. index.html <td> <label>{{learn ...

Creating an endless scrolling feature with Ionic 3

My tech stack includes symfony3 and FosRestBundle for the backend, and Ionic 3 for the frontend development. While attempting to implement an InfiniteScroll feature following the Ionic documentation, I encountered an issue where only the loading text and ...

Is there a way to eliminate the line that appears during TypeScript compilation of a RequireJS module which reads: Object.defineProperty(exports, "__esModule", { value: true });?

Here is the structure of my tsconfig.json file: { "compileOnSave": true, "compilerOptions": { "module": "amd", "noImplicitAny": false, "removeComments": false, "preserveConstEnums": true, "strictNullChecks": ...

Angular 2+: The art of creating an instance of a class using data retrieved from the backend

Within my Angular app, I have a Customer class and an ICustomer interface. interface ICustomer { <-- obtained from backend id: number; name: string; address: string; // additional properties } class Customer { <-- widely used in th ...

The Child/Parent arguments in Typescript methods cannot be assigned

Why is this not working in TypeScript? class Parent { id: string = '' } class Child extends Parent{ name: string = '' } const fails: (created: Parent) => void = (created: Child) => { return }; const failsToo: ({ create ...

Error encountered: `npm ERR! code E503`

While attempting to execute npm install on my project, which was cloned from my GitHub repository, I encountered the following error: npm ERR! code E503 npm ERR! 503 Maximum threads for service reached: fs-extra@https://registry.npmjs.org/fs-extra/-/fs-ex ...

Unit testing Firebase function with Jest for mocking

Currently, I am in the process of developing unit tests and facing challenges with mocking Firebase functions while specifying the return type upon calling them. The code snippet below illustrates what I intend to mock (account.service.ts) and provides ins ...

The data table fails to display updated information from the data source

After updating the data-array (FileDto), I am unable to see any changes reflected in the Datatable. I have tested outputting the data using ngFor, and it works perfectly fine. Here is the HTML code: <ngx-datatable class="material striped" [rows]= ...

Error: passport-local-mongoose does not have a createStrategy or authenticate function

Currently, I am working on enhancing features of a starter project available at this repository. The specific task at hand involves integrating user login functionality using passport-local-mongoose. In my attempts to utilize different strategies for impl ...

Tips for setting up a listener for when the month changes in an ion-datetime object

When the user selects a different month, I need to update the highlightedDates by calling a query to retrieve all the dates of that specific month. This currently works if the user manually chooses a month and year using the top button, but not when they c ...

After logging out, Next-auth redirects me straight back to the dashboard

In my NextJS application, I've implemented a credential-based authentication flow along with a dashboard page. To handle cases where an unauthorized user lands on the dashboard route, I've created a custom AccessDenied component. In the getServer ...

Exploring TypeScript Heartbeat functionality with Nodejs ws module

I am currently in the process of setting up a WebSocket server using NodeJs and TypeScript. The WebSocket server implementation I have chosen is from the ws package, supplemented by the @types/ws package for typings. My goal is to have the server send out ...

How can one overcome CORS policies to retrieve the title of a webpage using JavaScript?

As I work on a plugin for Obsidian that expands shortened urls like bit.ly or t.co to their full-length versions in Markdown, I encounter a problem. I need to fetch the page title in order to properly create a Markdown link [title](web link). Unfortunatel ...

Encountering issues with accessing properties of undefined while chaining methods

When comparing lists using an extension method that calls a comparer, I encountered an error. Here is the code snippet: type HasDiff<T> = (object: T, row: any) => boolean; export const isListEqualToRows = <T>(objects: T[], rows: any[], has ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Trigger the D3 component to re-render in React after a state change occurs in the parent component

My React project consists of two components written in TypeScript. The first component contains menus, and I am using conditional rendering to display different content based on user selection. <Menu.Item name="graph" active={activeItem ...

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...