Creating an Array and declaring its type in Angular 5 using TypeScript

My goal is to create an array from a declared type.

I can achieve this using enums, like so:

export enum Day {
    SU = 'su',
    MO = 'mo',
    TU = 'tu',
    WE = 'we',
    TH = 'th',
    FR = 'fr',
    SA = 'sa',
} 

getDays(): String[] {
    return Object.values(Day);
}

The output will be ['su', 'mo' etc. ]

I am looking for a similar solution with the following approach:

export declare type WeekDays = 'su' | 'mo' | 'tu' | 'we' | 'th' | 'fr' | 'sa';

and expecting a similar output as: ['su', 'mo' etc. ]

Have any ideas? I have tried using Object.entries() and Object.getOwnPropertyNames(), but unfortunately, they did not work.

Answer №1

WeekDays is considered a type in programming, and unlike objects at runtime, types do not have any presence during execution. This means that we cannot access any information stored within a type at runtime. Enums, on the other hand, are represented as objects during runtime, allowing us to extract information from them. To learn more about the distinction between types and values, you can visit this link.

Without implementing a custom compiler transformation (which involves replacing the default compiler with a tailored version that provides extra details), our only option is to create a function for retrieving values. This function requires us to input an object literal that includes the exact strings defined in the enum. Although this may involve restating the strings, the compiler will verify that no additional strings are added and none are missing, ensuring accuracy:

export declare type WeekDays = 'su' | 'mo' | 'tu' | 'we' | 'th' | 'fr' | 'sa';
function getValues<T extends string>(values: { [P in T]: P }) : T[]{
    return Object.values(values);
}
// All values correctly stated
getValues<WeekDays>({fr: 'fr', mo: 'mo', sa:'sa', su:'su', th:'th', tu:'tu', we:'we'})
// Incorrect value provided
getValues<WeekDays>({fr: 'frrr', mo: 'mo', sa:'sa', su:'su', th:'th', tu:'tu', we:'we'})
// Missing value
getValues<WeekDays>({mo: 'mo', sa:'sa', su:'su', th:'th', tu:'tu', we:'we'})
// Extra value
getValues<WeekDays>({funDay: 'funDay', fr: 'fr', mo: 'mo', sa:'sa', su:'su', th:'th', tu:'tu', we:'we'})

Answer №2

When working with TypeScript, it's important to remember that all types are only available as metadata and cannot be accessed during runtime. This means that the list of valid strings in your string literal type cannot be retrieved at runtime.

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

Angular - Transform calendar dates to a lively green upon initial popup activation

I'm looking to customize my calendar so that all the dates in my list have a green background when the calendar is opened. ngOnInit(): void { this.roomService.getReservableDatesFromRoom(room.roomName).subscribe(data => { for (let i = 0; i ...

Guide to making a ng-bootstrap modal that retains a component's state

I am currently working on implementing a modal with Angular by following a tutorial on the ng-bootstrap website ( - in the "Components as content" section). However, I am facing a challenge where I want the component displayed in the modal to retain its st ...

In Angular2, declaring variables with log={} and dynamically adding log details like [{id: "Logs List Details1"}, {id: "Logs List Details2"}] is a simple process

When declaring a variable with log = [{id: "Logs List Details1"},{id: "Logs List Details2"},....etc}] dynamically, issues arise when pushing dynamic data to it. If the data is static and pushed incrementally, it exceeds the page limit. However, if only one ...

Error encountered in Jest mockImplementation: Incompatible types - 'string[]' cannot be assigned to 'Cat[]' type

Recently, I've been writing a unit test for my API using Jest and leveraging some boilerplate code. However, I hit a snag when an error popped up that left me scratching my head. Here is the snippet of code that's causing trouble: describe(' ...

When I try to load JSON data using the http.get() method in my Angular 2 template, it returns

I've encountered an issue while attempting to read and parse a local json file into a custom class I created. The problem arises when trying to access properties of the class, as it throws errors indicating that the class is either null or undefined. ...

The type '{ children: Element[]; }' does not include the properties 'location' and 'navigator' that are present in the 'RouterProps' type

Struggling to implement React Router V6 with TypeScript, encountering a type error when including Routes within the `<Router />` component. The error message indicates that the children property passed to the Router is of an incorrect type, despite u ...

Is it possible to declare two global variables with the same name in Angular?

There are two global variables that come from different third-party files with the same name. Previously, I would use them like this: declare var someVar; But now, how can I use both of these variables? declare var someVar; declare var someVar; Is th ...

Automatically Populate Data Table with Email Addresses

After logging into the application, I am using the angular-datatables package from https://www.npmjs.com/package/angular-datatables. The search bar in the datatable auto fills with the email id upon login as shown in the image Data Table. However, I need ...

Circular dependency detected between TransferHttpCacheModule, LocalizeRouterModule, and TranslateModule

I am in need of the following modules for my project: TranslateModule LocalizeRouterModule TransferHttpCacheModule This particular combination of modules seems to be causing a cyclic dependency issue. TranslateModule with TransferHttpCacheModule - works ...

Issue with ng2-charts not rendering properly on the client side when utilized in Angular version 2.0.0-beta-17

Struggling with using ng2-charts in my Angular 2 app and encountering some challenges. app.ts import {Component} from 'angular2/core'; import {CHART_DIRECTIVES} from 'ng2-charts/ng2-charts'; @Component({ selector: & ...

Troubleshooting the issue of process.nextTick not being recognized in Calgolia places.js

After successfully implementing Algolia's places.js in my Angular 7 project using NPM, I encountered an issue. I have integrated a form where one of the fields should be an input. <form [formGroup]="myForm"> <pre style="color: white; b ...

Discover the versatility of TypeScript by dynamically adding methods to a class!

Are there any examples of dynamically extending a class with a method in TypeScript? I attempted the following: UsersBlocksMyOrders.prototype.myFunc = function():any{ alert('23434'); }; However, the compiler is giving me an error. ...

"Encountered a problem when trying to import stellar-sdk into an Angular

Our team is currently working on developing an app that will interact with the Horizon Stellar Server. As newcomers in this area, we are exploring the use of Angular 8 and Ionic 4 frameworks. However, we have encountered difficulties when trying to import ...

What would be the optimal type for the second argument of the `simulate` method?

When using the simulate function, I am familiar with code like this: simulate("change", { target: { value: '7' } }); However, if my onChange function requires an object as a parameter, what should I pass in the second argument? interface myObj ...

Looking to address excessive re-renders caused by Redux on a single page and seeking assistance in identifying and resolving the problem

Currently, I am in the process of developing the dashboard website for a music theory application company. This platform will allow users to manage various aspects such as their personal information, courses, assignments, and media content. The dashboard ...

Can Angular be utilized for developing an email application?

Can an email application be developed using Angular? I attempted to incorporate a nodejs script, but encountered issues when using the nodejs script within an Angular TS file, resulting in the following error: Error: Module not found: Error: Can't re ...

How can I invoke a function in a Component using an HttpInterceptor?

Can a function in a Component be triggered from an HttpInterceptor? @Injectable() export class HttpResponseInterceptor implements HttpInterceptor { // constructor(@Inject(DOCUMENT) private document: any) { } intercept(req: HttpRequest<any>, ...

How can a Firestore Timestamp object be correctly created within a rules test data set?

I am in the process of writing tests for Firestore rules, focusing on testing rules that control when actions can be executed based on a timestamp stored in the document. It is important to note that the rules will utilize rules.Timestamp rather than Java ...

When implementing .forEach, an object within the array is mistakenly duplicated

Struggling to populate an array of objects with unique data using the .forEach function to display feedback in the Administrator page of my portfolio. However, encountering an issue where the objects from 'd' are getting duplicated in the 'f ...

Tips for Automatically Populating Content in The Quill Js Editor Within Angular

Seeking some assistance. In my Angular application, I have received data from an API. I am trying to prefill the Quill Editor input box with the obtained data, but unfortunately, it doesn't accept the value attribute. This approach didn't work: ...