Can an array be typed in TypeScript to include all keys of an enum?

Is there a way to type the enum array so that it must include every value of the EPostFromField enum?

This pertains to a mongodb schema, where the goal is to future-proof the enum field in case more enums are added later. The aim is to have the compiler detect an error if the array does not contain all the enum values.

Additionally, it would be ideal to find a solution that ensures the enum array values are all unique :)

export const enum EPostFromField {
  Resident = 'resident',
  AdminUser = 'admin-user', // Admin <user name>
  BoardUser = 'board-user', // Board <user name>
  AdminSociety = 'admin-society', // Admin <community name>
  BoardSociety = 'board-society', // Board <community name>
}

showPostAs: {
    type: String,
    default: EPostFromField.Resident,
    enum: [
      EPostFromField.Resident,
      EPostFromField.AdminUser,
      EPostFromField.BoardUser,
      EPostFromField.AdminSociety,
      EPostFromField.BoardSociety,
    ] as EPostFromField[], // DEVNOTE: Enhance typing to enforce inclusion of *every* unique key from the enum
  },

Answer №1

To implement a string enum, you can follow these steps:

enum EPostFromField {
    Resident = "Resident",
    AdminUser = "AdminUser",
    BoardUser = "BoardUser",
    AdminSociety = "AdminSociety",
    BoardSociety = "BoardSociety"
}

const epostFromFieldKeys = Object.keys(EPostFromField);

const epostFromFields = epostFromFieldKeys as EPostFromField[]

You can test this code snippet in the provided playground link.

By ensuring unique values in the enum, the resulting array will contain only unique elements.

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

Refreshing React Component with Latest Data from Firestore

I'm facing an issue with my chrome extension that retrieves data from Firestore and displays it on the frontend. Currently, whenever new data is added, I have to manually refresh the page to see the updates, which is not very user-friendly. How can I ...

Error: The value of 'FuId' property is not defined and cannot be read

In the process of developing a small application, I am dealing with the concept of Risk Areas, Family Units, and their members. The Risk Areas are divided into 3 groups with IDs 1, 2, and 3 respectively. Each Risk Area consists of multiple Family Units, wi ...

Scala: A simple method to store Arrays in a Set or Map

Due to the inability of == to work with Arrays, I am struggling to create a Set of Arrays or Map with Array keys without having to convert them into Vectors or Lists for performance reasons. Is there a more efficient way to establish natural comparison a ...

Collection of ArrayLists containing Integers populated with varying combinations

If I have an array of Integer Wrap Objects... Integer[] p = new Integer[]{7, 5, 3, 2}; //Variable Length I need to create an array of ArrayList with specific values. 2 3 3, 2 5 5, 2 5, 3 5, 3, 2 7 7, 2 7, 3 7, 3, 2 7, 5 7, 5, 2 7, 5, 3, 2 7, 5, 3, 2 W ...

How can variables from state be imported into a TypeScript file?

Utilizing vue.js along with vuetify, I have a boolean value stored in state via Vuex defined in src/store/index.ts (named darkMode). This value is used within one of my view components inside a .vue file. However, I now wish to access the same variable in ...

Can you explain the concept of static in Typescript?

Exploring the distinctions between the static and instance sides of classes is addressed in the Typescript documentation on this page. The static and instance sides of classes: understanding the difference In object-oriented programming languages like ...

When using Typescript inheritance, the datatypes shown in IntelliSense are unexpectedly listed as "any" instead of

In my Typescript code, I have a small implementation where a class is either implementing an interface or extending another class. interface ITest { run(id: number): void } abstract class Test implements ITest { abstract run(id); } class TestEx ...

How can I restrict a generic type to include the new() method?

Is there a way to create a function similar to the following in TypeScript? createEntity<TEntity>(): TEntity { return new TEntity(); } In C#, we can achieve this using: void TEntity CreateEntity<TEntity>() where TEntity : new() How would ...

Typescript's dynamic React component and its conditional types

I am currently working on a dynamic React component and I am facing an issue with properly passing the correct propType based on the selected component. The error arises when using <SelectComponent {...props.props} /> because the props do not match t ...

Angular module cannot be located

While working on implementing a chat feature for my project using sockJS and STOMP, I encountered several challenges with installing these two libraries. Despite attempting various methods such as installation from index.html, npm install, and manual downl ...

How can you enhance a component by including additional props alongside an existing onClick function?

As a newcomer to React and TypeScript, I've created a simple component that looks like this: const CloseButton = ({ onClick }: { onClick: MouseEventHandler }) => { const classes = useStyles(); return <CloseIcon className={classes.closeButto ...

You have to include the necessary request body in the front-end request to address the

After successfully testing a POST request to add a new entity to the database from my project back-end using Postman, I encountered an error when trying to do the same from the front UI (I'm using Angular 4): Required request body is missing. Failed ...

I attempted to retrieve the id field of a jsonwebtoken following the user's login, but unfortunately, I was unable to access it

While working on the backend of my application, I encountered an issue trying to save the id field from a JSON Web Token (JWT) to an item that I created after a user logs in. Although I am able to log the JWT information successfully, I'm facing diffi ...

Determine the Number of Nodes in a JSON Array Response using SoapUI

After gaining valuable knowledge from SoapUI, I've hit a roadblock with one particular issue. The payload that is returned to me looks like this: [ { "@c": ".CreditPaymentInfo", "supplementalInfo": null, "date": "06/30/2015 1 ...

Displaying multi-dimensional arrays through the console in JavaScript and showcasing their elements

My array is supposed to have 140 indexes in a single format like this: array:[0-140] //however, it currently appears as: array: [ 0: [0-99], 1: [100-140] ] I've confirmed multiple times that it is just one array of objects. Why is it s ...

The behavior of an Angular 2 method varies depending on whether it is called in ngOnInit or triggered by a button

In the process of constructing a website with the Angular 2 CLI, I have encountered a perplexing issue. Specifically, I am working on a page that features a reactive form and have developed a method named addQuestion() that is invoked within the ngOnInit l ...

Retrieving selected values from a dynamic Primeng checkbox component

Within my Angular app, I am managing an array of questions. Each question includes a text field and an array of string options to choose from. The questions are retrieved dynamically from a service and can be updated over time. To allow users to select mul ...

To transform the array into an associative array, eliminate all numerical indices

After running a print_r() statement, I have an array that looks like this: //print_r($theArray) array (size=5) 0 => array (size=1) 'Animal' => string 'Dog' (length=3) 1 => array (size=1) 'House& ...

What is the best way to eliminate the final character in an input value once it has passed through regex validation in Angular8

Hello! I am attempting to remove the last digit of a string and update the input value each time my function checks if the input value passes a regex test on keypress. Initially, it works correctly, but then it adds an extra digit. After that, it works a ...

cookies cannot be obtained from ExecutionContext

I've been trying to obtain a cookie while working with the nestjs and graphql technologies. However, I encountered an issue when it came to validating the cookies by implementing graphql on the module and creating a UseGuard. It was suggested that I ...