Discovering the data type in Typescript through the use of Generics

In my data structure, I am using generics to build it. However, when I try to populate data, I encounter the need to convert simple formats into the correct types. The issue arises as the class is configured with Generics, making it difficult for me to determine the type of data in other parts of the code.

Below is a snippet extracted from my code:

export class Field<T> {
    private Name_: string;
    private Value_: T;

    constructor(FieldName:string, Data?:T) {
        this.Name_ = FieldName;
        if( Data !== undefined) {
            this.Value_ = Data;
        }
    }

    /**
     * Get the data value from this class
     * @returns T The value from Value_
     */
    get Value(): T {
        return this.Value_;
    }

    get Type(): string {
        return typeof this.Value_;
    }

    /**
     * Set the data into the data value
     * @param Data T Generic Data member as the raw data to be stored in the field.
     */
    set Value(Data:T) {
        this.Value_ = Data;
    }
}

This example illustrates the challenge I am facing. My data structure (Field) is characterized by a generic (Field), and I anticipate that the data's value should match that type.

I have been attempting to test this but have been unsuccessful in retrieving the type from the Object (as it belongs to the Field type). Therefore, my approach was to ascertain the type of the internal data field.

    describe('Get Type of Value', () => {
        let TestField:Field<number> = new Field<number>('Age', 32);
        it('should return the value type from the definition', () => {
            expect(TestField.Type).toBe('number');
        });
    });

However, the test fails showing that the Type getter function is returning undefined.

 FAIL  
    Expected value to be (using Object.is):
      "number"
    Received:
      "undefined"

Answer №1

Your solution is working perfectly:

TypeScript Playground

It seems like your test runner (maybe Jest?) is causing some issues. Try moving the let newUser... declaration inside the

it('...', () => { /* here */ })
block and give it another go.

Just a heads up, in JavaScript convention, variables should be named using camel case.

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

Exploring Real-Time Typescript Validation in Next.JS

Checking for TypeScript errors in Next.JS can only be done with npm run build (or yarn build). Unfortunately, running npm run dev won't display TypeScript errors, which is quite inconvenient as it would be better to have them visible in the Terminal ...

If you're trying to work with this file type, you might require a suitable loader. Make sure you

Attempting to utilize Typescript typings for the Youtube Data API found at: https://github.com/Bolisov/typings-gapi/tree/master/gapi.client.youtube-v3 Within the Ionic framework, an error is encountered after running 'Ionic Serve' with the follo ...

Required Ionic form field alert

Currently, I am developing a new app using ionic 3 and I am facing an issue with making inputs mandatory in my ionic-alert controller. Despite going through the ionic-component documentation and api documentation, I couldn't find a solution on how to ...

Working with a function in the stylesheet of TypeScript in React Native allows for dynamic styling

When attempting to use variables in my StyleSheet file, I encounter a type error even though the UI works fine. Any suggestions on how to resolve this issue? type buttonStyle = (height: number, width: string, color: string) => ViewStyle; export type St ...

Update the form field with today's date in a JHipster application

In our current project in JHipster, we are facing a challenge with setting the default value of a form field as the current date. JHipster offers a moment format for dates, which is essentially an ngbdatepicker. However, when attempting to change the inpu ...

Variable Scope is not defined in the TypeScript controller class of an AngularJS directive

I have implemented a custom directive to wrap ag grid like so: function MyDirective(): ng.IDirective { var directive = <ng.IDirective>{ restrict: "E", template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGrid ...

Arrange items by their keys while keeping their current values in order to correspond to the array sequence

I have two sets of data. First one is in the form of (footerMenuOptions): [{Home: true}, {About: false}, {Features: false}, {Contact: false}]  The second set is in the form of (this.navbarMenuOptions): ["Home", "About", "Features", "Contact"] Occasio ...

Creating a custom data type for the Tanstack table filtering function

I developed a unique filter function specifically for enhancing the functionality of Tanstack Table by utilizing fuse.js. Despite my efforts, TypeScript consistently raises concerns when I try to define the type for my custom function. My goal is to alig ...

Creating TypeScript atom packages

Has anyone successfully implemented this before? I couldn't locate any assistance for it. If someone could provide references to documentation or existing code, that would be great. I know that Atom runs on Node and that there is a TypeScript compil ...

Exploring the method to retrieve a dynamically added property in Typescript

My React Component Loader receives certain props. The contentAlign property is only available when the local property exists and its value is 'relative'. I am encountering an error when trying to include contentAlign in the props, and I cannot ...

Is there a way to optimize app speed in Angular2 by importing CommonModule and RouterModule in a centralized location?

I find myself constantly importing these two modules in almost every component: import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; Is there a way to import them only once in the global app. ...

Type returned by a React component

I am currently using a basic context provider export function CustomStepsProvider ({ children, ...props }: React.PropsWithChildren<CustomStepsProps>) => { return <Steps.Provider value={props}> {typeof children === 'function&ap ...

Retrieving an array of objects from an API and attempting to store it using useState, but only receiving an empty

I have been working on fetching data from an API, storing it in Redux store initially, and then attempting to retrieve it using useSlector to finally save it in local state. Despite getting the data when I console.log it, I am unable to successfully store ...

What is the cause of the error message "property 'map' is undefined"?

I am currently working on a service that looks like this: public getUsers() { return this.httpClient.get(environment.BASE_URL + `api/all`); } In my component, I have implemented the ngx-bootstrap table to display the user data. import { Component, OnI ...

Error encountered when utilizing a mixin in TypeScript due to a parameter issue

Recently, I delved into learning Typescript and decided to experiment with the mixin concept. The code snippet below may seem trivial, but it's all part of the learning process. Surprisingly, everything runs smoothly except for line 42, myInput.sendKe ...

Deciphering intricate Type Script Type declarations

I am seeking clarification on how to utilize the object type for sending headers, aside from HttpHeaders provided in the HTTPClient declaration. While working with Angular HttpClient, I aim to include headers using an Object. However, I am unsure of how t ...

You cannot utilize Lesson as a JSX Component in Next JS TypeScript

Below is my updated page.tsx code: import Aspects from '@/components/Aspects'; import FreeForm from '@/components/FreeForm'; import Lesson from '@/components/Lesson'; import React from 'react'; import { Route, Route ...

What is the reason for not hashing the password in this system?

My password hashing code using Argon2 is shown below: import { ForbiddenException, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { AuthDto } from './dto'; import * as arg ...

Experiencing a problem with Typescript validation while integrating Storybook with Material-UI (

Encountering a Typescript validation issue while attempting to pass args as children to a Material-UI button in Storybook :-/ Any suggestions on how to resolve this and avoid the Typescript error? I suspect it is caused by not passing a ReactNode. Thanks ...

The field list contains an unidentified column named 'Test.computerIDComputerID'

I am currently navigating through the syntax of typeORM and have been stuck troubleshooting an issue for quite some time. It appears that whenever I utilize the find() function in typeORM, a query is generated with a duplicated column from a relation. Here ...