Guide on setting a default value for a variable within a Typescript class

In the process of developing a component to manage information about fields for form use, I am in need of storing different data objects in order to establish generic procedures for handling the data.

export class DataField<T> {
    /**
     * Field name (e.g., database column name, JSON field)
     */
    private Name_: string;
    private Size_: number;
    /**
     * The data type associated with this field. For example: String, Boolean, etc. This is internally set and not defined by an external reference
     */
    private Type_: T;

    /**
     * Constructor method
     * @param FieldName string Name of the Field
     * @param FieldSize number Field Size
     */
    constructor(FieldName:string, FieldSize:number) {
        this.Name_ = FieldName;
        this.Size_ = FieldSize;
    }

    /**
     * Retrieve the data type of the value
     * @returns string The type of the value
     */
    get Type(): string {
        return (typeof this.Type_).toString();
    }
}

The issue I am encountering is that the Type_ field is not initialized with any value, therefore it remains undefined all the time. When creating a DataField instance with a generic type, it may look like this:

new DataField<string>('FullName', 32);

With the generic type T now being string, my objective is to properly assign a value to the Type_ variable so that the call to get Type() will correctly return a string.

Answer №1

When constructing your object in TypeScript, remember to pass the type as a parameter to the constructor instead of explicitly setting it as a generic:

class DataField<T> {

    constructor( 
        private type: {new (...args): T}, 
        private fieldName: string, 
        private fieldSize: number) {}

    public getType(): string {
        return this.type.name;
    }
}

const field = new DataField(String, 'name', 256);
console.log(field.getType()); // outputs "String"

It's important to understand that classes in JavaScript are essentially functions and the class keyword is just a shortcut syntax. In JavaScript, "Types" are represented by constructors which, when called with new, create objects with the specified prototype.

Although a generic was used in the example provided, it's not necessary for the current implementation of the class. You could replace {new (...args): T} with {new (...args): any} without affecting functionality. However, generics become useful when dealing with a data container class that needs to return values with specific types:

class DataContainer<T> {
   // other class stuff

   public getValue(): T {
      // do stuff to return value
   }
}

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

Ensure that you call setState prior to invoking any other functions

Is there a way to ensure that the setSearchedMovie function completes before executing the fetchSearchedMovie(searchedMovie) function? const { updateMovies, searchedMovie, setSearchedMovie } = useContext(MoviesContext); const fetchMoviesList = (ev ...

Customizing Angular Forms: Set formcontrol value to a different value when selecting from autocomplete suggestions

How can I mask input for formControl name in HTML? When the autocomplete feature is displayed, only the airport's name is visible. After users select an airport, I want to show the airport's name in the input value but set the entire airport obje ...

Hovering over a table cell triggers a popup in Angular

Inserted a class into <td><span class="only-show-on-hover"></span></td> CSS code for the class td span.only-show-on-hover { visibility: hidden; } td:hover span.only-show-on-hover { visibility: visible; } Code for dialog box < ...

Checking for undefined based on certain conditions

When looking at the following code snippet type stringUndefined = "string" | undefined; type What<T> = T extends undefined ? "true" : "false"; const no : What<stringUndefined> = ""; The value of ' ...

Is there a way to execute the run function of a different Component in Angular 7 without causing the current

Is there a way to execute the ngOnInit() function from one component inside another component without needing to refresh the existing page? ...

Guide on bringing in Typescript definition that exports a lone variable

The "@types/dd-trace" library defines a single variable called trace in the type definition for the "dd-trace" library. declare var trace: TraceProxy; export = trace; declare class TraceProxy extends Tracer { /** * Initializes the tracer. This s ...

Discovering the most efficient route between two locations within a grid of values

I'm currently working on a game where I need to find the shortest route between two points. In my map, I have a 2D array called matrix: Node[][], class Node{ index: { x: number, y: number }, isAvailable: boolean } The goal is to ...

Using TypeScript, apply an event to every element within an array of elements through iteration

I have written the code snippet below, however I am encountering an issue where every element alerts the index of the last iteration. For instance, if there are 24 items in the elements array, each element will alert "Changed row 23" on change. I underst ...

Utilize Typescript to generate an object that contains a partial interface

Seeking assistance with an issue. We are working with two interfaces: interface IUserEntity { Id: number; FirstName: string; LastName: string; } interface IUserEntityMethods { GetFullName(): string; } I am trying to create an object tha ...

Error with Array type encountered in Typescript's find method

I am encountering an issue with code that looks like this: type X = { test: number; x: number; }[]; type Y = { test: number; y: number; }[]; type Z = { test: number; z: number; }[]; export const testFunc = (arg: X | Y | Z) => { return a ...

Limit function parameter types to object keys

Is it possible to constrain my function parameter to match the keys of an object? I want to achieve something similar to this: export const details = { x: { INFO_x: 'xxx' }, y: { I ...

Explore Angular's ability to transform a nested observable object into a different object

My task involves mapping a field from a sub object in the response JSON to the parent object The response I receive looks like this: { "id": 1, "name": "file-1", "survey": { "identifier": 1, "displayedValue": survey-1 } } I am attempting ...

Loading data into the Nuxt store upon application launch

Currently, I'm working on an app using Nuxt where I preload some data at nuxtServerInit and store it successfully. However, as I have multiple projects with similar initial-preload requirements, I thought of creating a reusable module for this logic. ...

Issue with the MUI Autocomplete display in my form

Recently, I started using Material UI and Tailwind CSS for my project. However, I encountered an issue with the Autocomplete component where the input overlaps with the following DatePicker when there is multiple data in the Autocomplete. I have attached a ...

Encountering Problems when Converting Vue Application from JavaScript to TypeScript with Vue and Typescript

Currently, I am in the process of converting a Vue project from JavaScript to TypeScript without utilizing the class-style syntax. These are the steps I took: I ran: vue add typescript I went through all my .vue files and: Indicated that TypeScript ...

Creating a custom Angular filter to group every 3 items within an iteration into a new div container

When attempting to organize three instances of app-story-preview within a wrapper div using a ngFor loop, I encountered the following code: <ng-template [ngIf]="stories.length > 0" [ngIfElse]="empty"> <cdk-virtual-scroll-viewport [itemSize ...

What is the reason behind Rollup flagging code-splitting issues even though I am not implementing code-splitting?

In my rollup.config.js file, I have only one output entry defined as follows: export default { input: './src/Index.tsx', output: { dir: './myBundle/bundle', format: 'iife', sourcemap: true, }, plugins: [ ...

Converting a string[] to an EventEmitter string[] in Angular 4 with TypeScript: Step-by-step guide

Programming Language: Typescript – written as .ts files Development Framework: Angular 4 I'm currently working on an application that is supposed to add chips (similar to tags in Angular 1) whenever a user types something into the input box and hi ...

Utilizing Angular 16 to Link Component Input with Parent Route Parameter

Picture a scenario where there is a component (some.component.ts) in Angular 16 that retrieves the value for its foo property from activeRoute, specifically from the parent route. Take a look at the code snippet below: @Input() foo!: string; constructor(p ...

Compilation in TypeScript taking longer than 12 seconds

Is anyone else experiencing slow TypeScript compilation times when building an Angular 2 app with webpack and TypeScript? My build process takes around 12 seconds, which seems excessively slow due to the TypeScript compilation. I've tried using both ...