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

Apply CSS styling to the shadow root

In my preact project, I am creating a Shadow DOM and injecting a style element into the Shadow root using the following code: import style from "./layout/main.css"; loader(window, defaultConfig, window.document.currentScript, (el, config) => ...

Resolve the issue pertaining to the x-axis in D3 JS and enhance the y-axis and x-axis by implementing dashed lines

Can anyone assist with implementing the following features in D3 JS? I need to fix the x-axis position so that it doesn't scroll. The values on the x-axis are currently displayed as numbers (-2.5, -2.0, etc.), but I want them to be shown as percentag ...

TypeScript/Javascript - Error: The specified function is not callable

After recently delving into TypeScript, I found myself encountering an error in my code for a wheel mini-game on my app. The specific error being displayed in the console is: this.easeOut is not a function The relevant portion of the code causing the iss ...

The dispatch function of useReducer does not get triggered within a callback function

Can anyone assist me with this issue I am facing while using React's useReducer? I'm trying to implement a search functionality for items in a list by setting up a global state with a context: Context const defaultContext = [itemsInitialState, ...

The SunEditor onChange event does not reflect updated state information

software version next: 12.0.7 suneditor: 2.41.3 suneditor-react: 3.3.1 const SunEditor = dynamic(() => import("suneditor-react"), { ssr: false, }); import "suneditor/dist/css/suneditor.min.css"; // Import Sun Editor's CSS Fi ...

Refreshing the page causes TypeScript Redux to lose its state

custom/reducer/shoppingReducer.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { ShoppingReducerInitialState } from "../../types/reducer-types"; import { ProductItem, ShippingDetails } from "../../types/typ ...

Is it possible to create my TypeORM entities in TypeScript even though my application is written in JavaScript?

While I find it easier to write typeorm entities in TypeScript format, my entire application is written in JavaScript. Even though both languages compile the same way, I'm wondering if this mixed approach could potentially lead to any issues. Thank yo ...

Can you explain the distinction between needing ts-node and ts-node/register?

Currently, I am conducting end-to-end tests for an Angular application using Protractor and TypeScript. As I was setting up the environment, I came across the requirement to include: require("ts-node/register") Given my limited experience with Node.js, I ...

The function has been called but it did not return a

It seems that there is confusion surrounding the .toHaveBeenCalled() Matcher in Jasmine. While it should return a Promise that resolves when the function has been called, some users are experiencing it returning undefined instead. For example: it('sh ...

The proper method for specifying contextType in NexusJS when integrating with NextJS

I am currently facing a challenge while trying to integrate Prisma and Nexus into NextJS. The issue arises when I attempt to define the contextType in the GraphQL schema. Here is how I have defined the schema: export const schema = makeSchema({ types: [ ...

"Exploring the process of making a REST call from an Angular TypeScript client to

I'm currently developing a Sessions Server for a project at work. My dilemma lies in the fact that I'm struggling to find resources on how to make JavaScript HTTP calls from a server running with http.createServer() and server.listen(8080, ...) ...

rxjs - monitoring several observables and triggering a response upon any alteration

Is there a way to watch multiple observables and execute a function whenever any of them change? I am looking for a solution similar to the functionality of zip, but without requiring every observable to update its value. Also, forkJoin isn't suitable ...

`Upkeeping service variable upon route alteration in Angular 2`

Utilizing a UI service to control the styling of elements on my webpage is essential. The members of this service change with each route, determining how the header and page will look. For example: If the headerStyle member of the service is set to dark ...

The process of implementing ngOninit with asynchronous data involves handling data that may take

Within the ngOnInit method, I am calling a service method and assigning the return value to a member variable. However, when trying to access this variable later in the ngOnInit again, it seems that due to synchronization issues, the value has not been ass ...

A guide on selecting the best UI container based on API data in React using TypeScript

I have been developing a control panel that showcases various videos and posts sourced from an API. One div displays video posts with thumbnails and text, while another shows text-based posts. Below is the code for both: <div className=""> &l ...

Using the decorator in VueJS Typescript allows you to easily define dynamic computed properties

On my hands is a component structured like this: @Component({ computed: { [this.stateModel]: { get() { return this.$store[this.stateModel]; } } } }) class Component extends Vue{ @Prop({ de ...

Exploring the inner workings of the canDeactivate guard feature in Angular

Exploring the concept of guards in Angular has sparked a question in my mind. Why can't we simply have a class with a deactivate method that we can import and use as needed? The provided code snippets illustrate my confusion. export interface CanComp ...

Unable to trigger click or keyup event

After successfully implementing *ngFor to display my data, I encountered an issue where nothing happens when I try to trigger an event upon a change. Below is the snippet of my HTML code: <ion-content padding class="home"> {{ searchString ...

Implementing dynamic image insertion on click using a knockout observable

I'm utilizing an API to retrieve images, and I need it to initially load 10 images. When a button is clicked, it should add another 10 images. This is how I set it up: Defining the observable for the image amount: public imageAmount: KnockoutObserva ...

What could be causing my NodeJS Backend to not retrieve the data properly?

For a current project, I am tasked with building a mobile application using Flutter for the frontend and NodeJS for the backend. To facilitate this, I have acquired a VPS from OVHcloud running Ubuntu 20.04. Following various tutorials, I set up a server as ...