Is it possible to access the attributes of an interface in TypeScript without relying on external libraries?

Ensuring the properties of an interface align with an object that implements it is crucial for successful unit testing.

If modifications are made to the interface, the unit test should fail if it is not updated with the new members.

Although I attempted to utilize the ts-transformer-keys package for this purpose, it returned an error indicating it is not a function.

   interface Test {
      mem1: boolean,
      mem2: string
   }

My ideal scenario would involve executing:

   console.log(Object.keys(Test))

and receiving:

   ['mem1', 'mem2'];

Answer №1

During runtime, interfaces do not exist, making it impossible to extract any information from an interface at that time. To work around this limitation, you can create an object that mirrors all the keys of the interface. By specifying all keys, the compiler ensures that no extra keys are present, keeping the duplication in sync with the interface:

interface Test {
    mem1: boolean,
    mem2?: string
}


function interfaceKeys<T>(keys: Record<keyof T, 1>) {
    return Object.keys(keys) as Array<keyof T>
}

console.log(interfaceKeys<Test>({
    mem1: 1,
    mem2: 1
}))

console.log(interfaceKeys<Test>({ // error
    mem1: 1,
}))

console.log(interfaceKeys<Test>{
    mem1: 1,
    mem2: 1,
    mem3: 1,     // error 
}))

play

Answer №2

For those comfortable with incorporating it at compile time and are utilizing TypeScript >= 2.4.1, a solution is presented here.

To achieve this, one must include the ts-transformer-keys library, along with a custom transformer. With these in place, it becomes possible to generate a list of properties in the following manner:

import { keys } from 'ts-transformer-keys';

interface Props {
    id: string;
    name: string;
    age: number;
}

const propsKeys = keys<Props>();

console.log(propsKeys); // ['id', 'name', 'age']

Answer №3

To obtain the data, simply utilize the following code:

type SomeType = ClientType['birthdate']

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

Encountering issues with data binding functionality within the stepper component

Within my web application, I have implemented 2 input fields known as Course name (utilizing an Autocomplete component) and Price (utilizing an input component). Previously, upon selecting a specific Course name, the corresponding Price would be displayed ...

How can I utilize Angular services to transfer a count value to the Component?

I've been working on creating a coin counter for my application by developing a service specifically for counting coins. However, when I tried to use this service in one of my components where the count function is triggered, I encountered some diffic ...

Angular allows for the creation of a unique webpage layout featuring 6 divs

I am working on a project where I have an image of a car and I need to overlay 6 divs onto the image which can be selected with a mouse click. When a user clicks on one of the divs, it should change color. I've attempted using z-index, but it doesn&ap ...

What steps can I take to prevent receiving the error message "Certain components in XXX are not associated with the entity" in Strapi?

User I am facing an issue with my application's endpoint for adding a like to a post. The endpoint is supposed to receive the user id who liked the post and insert it, along with the number of likes (not crucial at this moment), into a database. To ac ...

Issue with Material UI DateTimePicker not submitting default form value

Currently, I am utilizing React for my frontend and Ruby on Rails for my backend. My issue lies in submitting the value from my materialUI DateTimePicker via a form. The problem arises when I attempt to submit the form with the default DateTime value (whic ...

How come the CSS for my angular ngx-mat-datetime-picker and mat-datepicker collide when they are both present on the same page?

Within the same form, I have two input fields stacked under each other. One is an ngx-mat-datetime-picker and the other is a mat-datepicker. Individually, they function correctly. However, when I open them for the second time, the one I opened first appear ...

Forcing a property binding update in Angular 2

Take a look at this particular component import {Component} from 'angular2/core' @Component({ selector: 'my-app', providers: [], template: ` <div> <h3>Input with two decimals</h3> <input type ...

Using MobX to alter observed observable values outside of actions is not permitted in combination with Ant Design components

When trying to upload files to the server and receive a response, I encountered an issue. If I override the onChange property of the Upload component (from antd), mobx starts throwing errors and the file uploading process gets stuck in the 'uploading& ...

Parsing difficulties encountered: the element 'ion-col' is unrecognized

As I strive to develop Ionic 4 applications, a new error continues to surface even after attempts to resolve the previous one. Following the creation of a custom component mentioned in this error (How to load other page inside of an ionic segment?), a new ...

Comparing JSON objects with JavaScript models: A guide

Currently I'm working with angular 2 and I have an array of data. data: MyModel[] = [ { id: 1, name: 'Name', secondName: 'SecondName' } In addition, I have created the interface MyModel: interface MyModel { id: number, nam ...

Tips for creating a page component in Next.js using props?

I've encountered an issue while trying to properly annotate the parameters of the Home function component. My initial attempt was to use: { events }: { events: Event[] }, but TypeScript is throwing an error, stating that Property 'events' do ...

In my Angular application, the Authentication JWT is securely stored by Firebase within the Session Storage. Does this implementation pose any security risks

In order to enhance the user experience of our Angular app, we have integrated Firebase Authentication with Session Persistence. This ensures that users don't need to log in again every time they refresh the page. As part of this process, we store the ...

Changing the second instance of a specific text in Angular

str = "oreo has oreo"; switch the 2nd instance of oreo with chocolate result = "oreo has choklate"; how to change specific occurrence of a string in Angular 8. ...

What is the best way to interpret the data from forkjoin map?

As a newcomer to angular and rxjs, I am seeking guidance on how to properly retrieve data from forkJoin using a map function. ngOnInit(): void { this.serviceData.currentService.subscribe(service => this.serviceFam.getAllFamilles().pipe( ...

I'm sorry, we couldn't locate the module: Unable to find the path '../types/index'

After spending an hour attempting to troubleshoot this issue, I am still unable to find a solution. I have stored index.d.ts in the types folder. The content of the types file is as follows: export interface tag { created_at: string id: nu ...

Utilize Angular 9 to fetch data from an API using the Get method, map them to a class, and

Seeking to extract information from a test URL and convert the data into a list, I aim to exhibit them in an alert/Loop for testing purposes. The dummy API URL being used is: The returned data follows this structure: {"status":"success","data":[{"id":"1" ...

Issue with string interpolation failing to correctly reflect the updated value from the service provider

I created a simple component to test string interpolation in HTML, <p>{{value}}</p> Here is the TypeScript file: export class HelloComponent implements OnInit { value: any; constructor(private service: ApiService) { this.value = ...

Using Angular: Binding Angular variables to HTML for display

I have a component with a ts file that contains HTML content as a variable. Let's say para1= <a href="www.google.com">sitename</a> more content I want to bind this paragraph in HTML as if it were actual HTML tags. sitename What is the ...

Is it possible to utilize an array of numbers as a data source in ng2-smart table?

Hey there, I'm currently facing an issue with populating ng2-smart-table with an array of numbers. When I try to display the table, all I see is 6 empty rows like this: https://i.stack.imgur.com/DZJjq.png Here's the code for the table: <ng2- ...

Error encountered in Next.js: The function 'useLayoutEffect' was not successfully imported from 'react' (imported as 'React')

I've been in the process of migrating an application from CSR (using webpack only) to SSR, and I'm utilizing Next.js for this transition. Following the migration guide provided by Next.js for switching from vite (specifically focusing on parts r ...