Verify if an entity (either an object or a class) possesses a specific attribute

Imagine having a class like this:

module MyModule {
    export class MyClass {
       x:number;
       y:number;
    }
}

Now, let's say we have a string called "x". How can we determine if MyClass has the property "x"?

If an instance of MyClass is created and we use the following code:

myClassInstance.hasOwnProperty("x");

It will return false unless "x" has a default value assigned. However, we don't want to set default values for each property. It would be ideal if we could accomplish this without actually creating an instance of MyClass.

Answer №1

When TypeScript is translated into JavaScript for execution, the type information included in the TypeScript code is no longer accessible. Therefore, checking types at runtime in TypeScript is not possible.


To perform type checks during compile-time, one can utilize interfaces as demonstrated in the example below:

interface IHasY
{
    y:any;
}

class MyClassC {
    x:number;
    z:number;
}

class MyClassD {
    z:number;
}

function Verify(param: IHasY)
{
    // Perform an action with param.y 
}

var objC = new MyClassC();
var objD = new MyClassD();

Verify(objC);
Verify(objD);

The line Verify(objD); would trigger a compilation error because the TypeScript compiler recognizes that objD belongs to the MyClassD class, which does not contain a property named

y</code as mandated by the <code>IHasY
interface.

Answer №2

Exciting news! I have just unveiled an upgraded version of the TypeScript compiler that enables you to compile a comprehensive list of all members within a class or interface. This new feature opens up a world of possibilities for developers, allowing them to easily access and analyze data structures.

export class Person {
    name: string;
    surname: string;
    age: number;
    country: string;
}

function printMembers(clazz: Class) {
    let fields = clazz.members.filter(m => m.type.kind !== 'function'); //exclude methods.
    for(let field of fields) {
        let typeName = field.type.kind;
        if(typeName === 'class' || typeName === 'interface') {
            typeName = (<Class | Interface>field.type).name;
        }
        console.log(`Field ${field.name} of ${clazz.name} has type: ${typeName}`);
    }
}

//then, somewhere in your code:
let p = new Person();
printMembers(p.constructor.getClass());

This capability produces the following output:

$ node main.js
Field name of Person has type: string
Field surname of Person has type: string
Field age of Person has type: number
Field country of Person has type: string

To dive deeper into this groundbreaking feature, visit this link

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

Is it possible to initialize ckeditor with a base64 encoded string?

Is there a way to open ckeditor using a base64 string as data? <ckeditor [editor]="Editor" data="Base64String???"> Alternatively, are you aware of any base64 docx viewers for angular? Thank you in advance! ...

Tips for identifying unnecessary async statements in TypeScript code?

We have been encountering challenges in our app due to developers using async unnecessarily, particularly when the code is actually synchronous. This has led to issues like code running out of order and boolean statements returning unexpected results, espe ...

What methods can I use to ensure that both variables are true and maintain their relationship in a logical 'and' statement?

The code snippet provided raises a question about the logic behind the declaration of variable x as a string: function sample(one: boolean, two?: string) { if (one || two) { const x: string = one ? 'hello' : two; // Type 'string | ...

Pass the variant value from Shopify/Restyle to the child component in a seamless way

Forgive me if this question has already been addressed elsewhere. Is there a secure method to transmit variant information to child components? I'm attempting to craft a personalized Button component using the useRestyle hook as outlined in the follo ...

What is the best method to completely uninstall Apollo-Angular along with all of its dependencies?

Once I added apollo-angular and @apollo/client to my project, I quickly realized that I no longer needed them. However, simply using "npm uninstall apollo-angular" and "npm uninstall @apollo/client" only removed the main folders but left behind other Apoll ...

What is the best way to stop webpack from generating typescript errors for modules that are not being used?

The directory structure is set up as follows: └── src ├── tsconfig.json ├── core │ ├── [...].ts └── ui ├── [...].tsx └── tsconfig.json Within the frontend, I am importing a limi ...

Transforming Excel data into JSON format using ReactJS

Currently, I am in the process of converting an imported Excel file to JSON within ReactJS. While attempting to achieve this task, I have encountered some challenges using the npm XLSX package to convert the Excel data into the required JSON format. Any as ...

Typescript and React: Unraveling the intricacies of complex

Is it possible to define custom types verified by a function in Typescript/React? Instead of using a simple 'string' type, I envision using a regex expression: interface Verify { email: /.+@.*\.com/g; } The specific regex above might not ...

Unexpected error: Angular 4 TypeScript validation issue - An object literal can only define recognized properties

excellent customer service import {Account} from '../models/Account'; export class AccountingService { domain: string = "http://localhost:3000/api"; constructor(private http: HttpClient) { } getAccounts(){ return this.http.get&l ...

Can you explain the significance of the angle brackets "<>" in a Typescript function declaration?

When working with TypeScript code, I often come across code enclosed in angle brackets, similar to HTML. Despite knowing that they are not HTML elements, and understanding that the content within the angle brackets represents types, I frequently encounter ...

Does the React memo function modify the component's prop type?

I've come across a strange issue where defining two components causes compilation errors when written separately but not when written in the same file. test3.tsx import React from "react"; type ValueType = number[] | string[] | number | st ...

What is the best way to update the displayed data when using Mobx with an observable array?

Is there a way to re-render observable array data in Mobx? I have used the observer decorator in this class. interface IQuiz { quizProg: TypeQuizProg; qidx: number; state: IStateCtx; actions: IActionsCtx; } @observer class Comp extends Rea ...

Do you have an index.d.ts file available for canonical-json?

I am currently working on creating an index.d.ts file specifically for canonical-json. Below is my attempted code: declare module 'canonical-json' { export function stringify(s: any): string; } I have also experimented with the following sn ...

Utilizing markModified inside a mongoose class that does not inherit from mongoose.Document

In my Typescript code using mongoose ODM, I am implementing a simple queue structure. The challenge arises when directly mutating an array instead of assigning a new value to it because mongoose doesn't automatically recognize the change. To resolve t ...

Unlocking the power of asynchronous methods within the useEffect() hook

When attempting to fetch an API within a useEffect(), I encountered the following error: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. Here is the code snippet that caused the error: -API being fetched: ex ...

Loading complex JSON data into objects in TypeScript can be a challenging and intricate task

Dealing with a unique JSON structure that needs to be loaded into a TypeScript model. The challenge arises from receiving the JSON as an object instead of an array from a third party source. Is there a method to successfully load this data into the model ...

Converting Enum into an array in TypeScript to return the keys of the Enum

After defining the following enum: export enum Types { Type1 = 1, Type2 = 2, ... } We can create an array based on this enum with the function below: export function EnumKeys<T>(obj: object): string[] { return Object.keys(obj) ...

The types 'X' and 'string' do not intersect

I have a situation where I am using the following type: export type AutocompleteChangeReason = | 'createOption' | 'selectOption' | 'removeOption' | 'clear' | 'blur'; But when I try to compress the cod ...

Angular version 5 and above introduces a new feature called "openFromComponent" within the Snackbar component, facilitating seamless communication

Angular (v5.2.10) Snackbar --| Introduction |-- I am facing a scenario where an Angular component named "Parent" is initializing an Angular Material Snackbar known as snackBar. The snackbar is being passed in the component called SnackbarMessage, which ...

What resources are available for creating the framework of a TypeScript package in DefinitelyTyped?

I am interested in making contributions to by providing new types similar to what can be found on https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types. I believe there must be a way to create a package from scratch or get started. I have ...