A guide to retrieving the types of optional properties within a class or interface using Typescript

class Data {
    ID: number;
    Activity?: string;
    public getDataType(name: string) {
    return typeof this[name];
    }

    constructor() { }
}

    let _data = new Data()
    _data.ID = 5

    console.log(_data.getDataType("ID")) // Returns number
    console.log(_data.getDataType("Activity")) //Returns undefined. But I want it to be string

I am looking to retrieve the types of all properties in my class, regardless of whether they have a value or not. However, when optional properties are not set, the getDataType function always returns undefined.

I could use an Interface instead of a Class, it doesn't matter. How can I solve this issue?

Thank you in advance!

Edit: My main objective is as follows.

I will receive data from a backend service with a model structure like the Data interface or class. Some properties of Data will be either numbers or strings and may be optional (potentially null or undefined). I want to display these fields to the user for editing on an HTML form, and then send the edited data back to the backend service for saving. When saving, I want to maintain the original data type. For example, if a field is a number, it should remain a number after the user's update and be sent to the backend endpoint as a number. I was using in HTML for each field. Because I want to dynamically generate HTML for each property using ngFor iteration. However, in order to preserve the value type (e.g. ensuring a number stays a number), I need to know the type of each property to display instead of . Therefore, my main goal is to dynamically preserve the data type according to my interface or class. I do not want to manually cast each field. If there is a different solution to achieve this, I would be happy to hear it.

Thank you once again!

Answer №1

By assigning the value to ID, you will receive a number type. Otherwise, it will be undefined. It is recommended to initialize the property at the beginning of the class or in the constructor to ensure you always get the desired type.

class Load {
  ID!: number;
  Action?: string;
  public getType(name: string) {
    return typeof (this as any)[name];
  }

  constructor(ID: number, Action = '') {
    this.ID = ID;
    this.Action = Action;
  }
}

Complete Code:

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

class Load {
  ID!: number;
  Action?: string;
  public getType(name: string) {
    return typeof (this as any)[name];
  }

  constructor(ID: number, Action = '') {
    this.ID = ID;
    this.Action = Action;
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <h1>Hello from {{ name }}!</h1>
    <a target="_blank" href="https://angular.dev/overview">Learn more about Angular</a>
  `,
})
export class App {
  name = 'Angular';

  ngOnInit() {
    let _load = new Load(1);

    console.log(_load.getType('ID')); // Outputs number
    console.log(_load.getType('Action')); // Should output string but currently outputs undefined
  }
}

bootstrapApplication(App);

View Stackblitz Demo

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

Define a distinct routing parameter that can be accessed through the ActivatedRoute instance

While working on setting up a router in my application, I encountered the need to define a query parameter that must be retrievable through the ActivatedRoute for compatibility reasons. Recently, I had to create some new sub-routes that do not follow the s ...

Implementing an Asynchronous Limited Queue in JavaScript/TypeScript with async/await

Trying to grasp the concept of async/await, I am faced with the following code snippet: class AsyncQueue<T> { queue = Array<T>() maxSize = 1 async enqueue(x: T) { if (this.queue.length > this.maxSize) { // B ...

Errors in the @babel/types during the ng build process in Angular version 8.2.14

When I execute the command 'ng build' for my Angular App, I encounter the following errors: ERROR in ../node_modules/@types/babel-types/index.d.ts:1769:96 - error TS1144: '{' or ';' expected. 1769 export function assertArrayE ...

Unable to link to '' because it is not recognized as a valid attribute of '' in Angular 2

I encountered an exception while working on my Angular 2 project and I'm struggling to figure out the cause. Below is the snippet of my code: ts: import {Component} from "@angular/core"; import {GridOptions} from "ag-grid"; import {RedComponentComp ...

Tips for personalizing the ngx-bootstrap datepicker

I am looking to enhance the ngx-bootstrap datepicker popup by adding a link or button within the calendar to select dates with a single click. I have been exploring ways to customize the datepicker without success. Currently, my project is built using Angu ...

Transfer my testing utilities from React Router version 5 to version 6

I am currently transitioning my project to React V6 router and encountering an issue with my test utility function. Every time I run the test, all my expectations fail because jest cannot locate the object. Has anyone faced this error during a similar migr ...

How to minimize scaffolding with Redux, React, and Typescript?

Is there a way to avoid the process of instrumenting my Redux-Aware components? The level of scaffolding required seems excessive. Take, for instance, the minimal code necessary to define a redux-aware component: class _MyActualComponent extends React.Co ...

What is the best way to pre-select a value in a mat-select within an Angular reactive form?

Assigning a default value to a drop-down using reactive forms didn't display as expected HTML <form [formGroup]="estadosForm" (ngSubmit)="aplicarCambios()"> <div class="campo campo-x2"> <mat-form-field> ...

"Optimize the appearance of group headers and items in Angular select style

I have integrated the ng-select library into my Angular project to create a dropdown menu. Here is an example of how I am using it: <ng-select [items]="flattenedSelectList" bindLabel="displayName" placeholder="Select speci ...

The OR operator in TypeORM allows for more flexibility in querying multiple conditions

Is there any OR operator in TypeORM that I missed in the documentation or source code? I'm attempting to conduct a simple search using a repository. db.getRepository(MyModel).find({ name : "john", lastName: "doe" }) I am awar ...

Failed to set the reference: The first argument includes an undefined property. This error occurred within the context of

My journey with Firebase began just 4 days ago, although I've been a bit inconsistent. My goal was to create a user in the database, and while the user was successfully created, I encountered an issue when trying to return to the profile picture page. ...

An array that solely needs a single element to conform to a specific type

While I was pondering API design concepts, a thought crossed my mind. Is it feasible to define a type in this manner? type SpecialArray<Unique, Bland> = [...Bland[], Unique, ...Bland[]]; However, the error message "A rest element cannot follow anoth ...

Controlling CSS Styles in Angular using TypeScript

Currently, I am working on an Angular project that involves dynamically populating a calendar. In addition to this, I have a range of dates and the task at hand is to modify the background for specific days within this date range. To manage dates effective ...

Using TypeScript to transform types: Array of objects with keys Kn and values Vn to an object with keys Kn and values Vn

I am looking to create a function that can process tuples with a specific structure like so: type Input = [ { key: K1, value: V1 }, { key: K2, value: V2 }, { key: K3, value: V3 }, // ... { key: KN, value: VN } ] The function should then output ...

Leveraging Angular 2 components within ASP.NET websites

I am in the process of transitioning the front-end portion of a website to Angular 2. The current setup involves a large ASP.NET 4.5 website. My plan is to create a separate Angular 2 project to accommodate future growth and eventually replace the ASP.NET ...

Is it possible for me to connect an npm run command as a task in a Gruntfile?

In the root directory of my site, I have made changes to the package.json file by adding the "scripts" hook below: "scripts": { "ngDeployDev": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ../../Scripts/ng-build-deploy/ngDeployDev.p ...

What is the approach to forming a Promise in TypeScript by employing a union type?

Thank you in advance for your help. I am new to TypeScript and I have encountered an issue with a piece of code. I am attempting to wrap a union type into a Promise and return it, but I am unsure how to do it correctly. export interface Bar { foo: number ...

Reactjs may have an undefined value for Object

I have already searched for the solution to this question on stackoverflow, but I am still confused. I tried using the same answer they provided but I am still getting an error. Can someone please help me resolve this issue? Thank you. const typeValue = [ ...

``There seems to be an issue with clicking an element in selenium

Having trouble with selenium while testing an angular site. Need to click on the pub name field on this screen: https://i.stack.imgur.com/i2NEO.png The side menu is open and here is the HTML: https://i.stack.imgur.com/0AxR9.png Tried waiting for the ele ...

The Angular Ivy strictTemplates error message states that the type 'Event' cannot be assigned to the type 'InputEvent' parameter

I'm feeling lost trying to figure out what's wrong with this code snippet: <input #quantity type="number" matInput formControlName="quantity" (input)="onQuantity($event, i)" placeholder="Quantity"/> onQuantity(event: InputEvent, i: number ...