How to retrieve the type of an undefined class in Typescript

I am looking for a way to determine the type of a value before using it. For example, I have values "y" and "N" that I want to convert to boolean when the field is boolean.
Instead of hardcoding the field, I am looping through the object to set the value. Is there a method to inspect the type before setting it?

Below is an illustration of an object:

export class test {
    id: string;
    foo: number;
    bar: boolean;
}

I attempted the following code, but it returns undefined until the value is set, potentially leading to overwriting what the object should be (e.g. turning into a string):

typeof test['bar']

Answer №1

Before using something, I prefer to determine its type

If dealing with classes, you can utilize the instanceof operator. For example:

class Foo{}
const foo = new Foo(); 
console.log(foo instanceof Foo); // TRUE

Additional Information

TypeScript does not offer any additional runtime type information compared to JavaScript. However, TypeScript does recognize and work well with existing JavaScript metadata checks such as instanceof and typeof.

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

What is the best way to utilize mapping and filtering distinct values in an array using TypeScript?

What is the best way to filter and map distinct elements from an array into another array? I've experimented with various methods but keep encountering a syntax error stating "Illegal return statement". My objective is to display only unique items f ...

What could be causing the Uncaught Error to persist even after using .catch()?

Check out this code snippet: function pause(ms:number) { return new Promise((resolve:any,reject:any) => setTimeout(resolve,ms)) } async function throwError(): Promise<void> { await pause(2000) console.log("error throw") throw new ...

Error: "Oops! The [test] view could not be located." Trace: [{file: vendorlaravelframeworksrcIlluminateViewFileViewFinder.php"

I created a web application using Laravel-5.8 for the backend and Angular-7 for the frontend, which includes functionality to send emails through Gmail. .env MAIL_DRIVER = smtp MAIL_HOST = smtp.gmail.com MAIL_PORT = 465 MAIL_USERNAME = <a href="/cdn-c ...

Prisma auto-generating types that were not declared in my code

When working with a many-to-many relationship between Post and Upload in Prisma, I encountered an issue where Prisma was assigning the type 'never' to upload.posts. This prevented me from querying the relationship I needed. It seems unclear why P ...

Steps to resolve the issue with "Error: StaticInjectorError(AppModule)[NgbDropdown -> ChangeDetectorRef]"

My attempt at creating a web app using Angular resulted in successful compilation with no errors. However, upon execution, the browser displays a blank page accompanied by the following error message: ERROR Error: Uncaught(in promise): Error: St ...

"Troubleshooting: The unique key prop is not functioning as expected with a

I am continuously receiving the warning message: Each child in a list should have a unique "key" prop. Even though I have assigned a key with an index number to my element, it does not appear in the HTML when inspecting via dev tools. The key values are a ...

Exploring the concept of the never type in TypeScript 2

Exploring the latest features in TypeScript 2.0, I came across the never type. It appears to be a clever method for defining the type of functions that do not have a return value. If I understand correctly, the never type can be assigned to any other type ...

The absence of the function crypto.createPrivateKey is causing issues in a next.js application

For my next.js application, I am utilizing the createPrivateKey function from the crypto module in node.js. However, I encountered an issue as discussed in this thread: TypeError: crypto.createPrivateKey is not a function. It seems that this function was a ...

Is it possible for an Angular2 HTTP request to retrieve the response body as binary data?

I'm facing an issue with a URL that returns HTML content with charset=iso-8859-7. Angular's HTTP request converts the data to utf8 by default, making it difficult for me to encode them back in iso-8859-7 properly. Upon researching, I discovered t ...

What is the best way to design a circular icon using OpenLayers?

I am currently incorporating openlayers into my ionic app and working on placing users on the map. I have encountered a problem as I am unsure how to apply custom CSS styling to the user element, which is not directly present in the HTML. In the screenshot ...

Utilizing the capabilities of the Highcharts regression plugin within the Angular 8 wrapper to effectively depict a trend line on a

Currently, I am attempting to incorporate a trendline into my spline plot using the Highcharts regression plugin. However, I'm struggling to locate any guidance on how to properly import the highcharts-regression plugin within my Angular component. I ...

Angular's HttpClient enables you to easily map an object to an array of properties

I have a scenario where I am calling an API that returns a JSON Object, and my task is to map this object to an array. Despite having the following code, I am not receiving any response or error after making the API call. export class Features { MenuId ...

Initiating the node js service locally

I have been working on a Node.js and Gradle application, but I'm having trouble figuring out how to run it locally. So far, I've done the Gradle build (./gradlew) and NPM run build (compile), with all my dependencies neatly stored in the node_mo ...

Encountering issues with installing Angular using npm due to errors

When I run npm install, I encounter errors. Though I can get it to work by using npm install --force, I prefer not to rely on the force flag. After reading through the errors, it seems like there might be a version compatibility issue, but I'm having ...

Encountering a problem with the chipGrid feature in Angular Material version

I am currently facing an issue with my angular material chip component. The versions I am using are Angular 16 and Material 16. Here are all my dependencies: "@angular/animations": "^16.0.4", "@angular/cdk": "^16.0.4&quo ...

ngRepeat momentarily displays duplicate items in the list

There is a modal that appears when a button is clicked. Inside the modal, there is a list of items that is populated by data from a GET request response stored in the controller. The issue arises when the modal is opened multiple times, causing the list t ...

Using Typescript with Angular: passing a generic Type to a function

When using Typescript for Angular 5 unit tests, I have created a function that can query the DOM and return an instance of the MyComponent class if it exists: function getMyComponent(hostFixture: ComponentFixture<any>): MyComponent { const debugEl ...

Effortless spring picture sharing thanks to @onetoonemapping

After uploading an image, I receive an image_id. However, when I use that id to upload a product, the product table shows an empty value in the image_id field. If you're unable to replicate the issue, you can access the code here. This is the struct ...

Setting a default value for a complex prop in Vue through Type-based props declarations

I'm struggling with this issue: Argument of type 'HelloWorldProps' is not assignable to parameter of type 'InferDefaults<LooseRequired<HelloWorldProps>>'. Types of property 'complexProp' are incompatible.ts( ...

What is the best way to refine React Component's props with Typescript?

My setup involves utilizing two specific components: Test and Subtest. The main functionality of the Test component is to provide visual enhancements and pass a portion of its props down to the Subtest component. Some props in the Subtest component are des ...