Creating an enum type array in TypeScript

I have developed a Typescript DTO to ensure type safety for a list of strings generated from an enum type.



export class ConnectedUserWithPhotosDTO extends UserWithPhotosDTO {
  userTags: keyof User["userTags"][]

  constructor(user: User, photos: ResponsePhotoDTO[]) {
    super(user, photos)
    console.log(user.userTags)
    this.userTags = user.userTags;
  }
}

The typescript compiler is throwing an error:

Type 'UserTags[]' cannot be assigned to type 'number | keyof UserTags[][]'.

It seems that the value of userTags is

number | keyof UserTags[][]

This is the enum definition I am working with.

export enum UserTags {
  FITNESS = 'Fitness',
  FOURTWENTY_FRIENDLY = '420 Friendly',
  MEDITATION = 'Meditation',
  DRINKS = 'Drinks',
  DOGS = 'Dogs',
  CATS = 'Cats',
  FASHION = 'Fashion',
  WINE_TASTING = 'Wine Tasting',
  FOODIE = 'Foodie',
  ART = 'Art',
  PARTYING = 'Partying',
  TRAVELIING = 'Travelling',
  GAMING = 'Gaming',
}

In the User class, UserTags is defined as:

 @ApiProperty({ enum: UserTags, isArray: true, default: [] })
  @Column('enum', { enum: UserTags, array: true, nullable: true, default: [] })
  userTags: UserTags[]

How can I specify just the type of keyof for a particular Enum value?

Answer №1

If we consider UserTags as an enum, the implementation could resemble this:

userTags: Array<keyof typeof UserTags>

Answer №2

Another way to achieve this is:

let userTags: User['tags'];

Answer №3

Your explanation is a bit perplexing due to the usage of keyof. It's unclear whether you are referring to the enum keys like "FITNESS", or the enum values such as "Fitness".

From the code snippet of the User and the error message, it appears that when you access user.userTags, you are retrieving the enum values. The type of these values corresponds to the enum itself, so the correct declaration would be:

userTags: UserTags[]

This aligns with the type in the User since we are assigning the userTags property based on User["userTags"].


Let's analyze the type

keyof User["userTags"][]
that was attempted and understand its interpretation.

User["userTags"] provides us with the userTags property of the User type. Based on your User code, User["userTags"] equals UserTags[], which represents an array of values from the UserTags enum, like

["Fitness", "Fashion"]
.

User["userTags"][] denotes our intention for an array of these values. However, it's already an array, leading to a request for an array of arrays of enum values: UserTags[][], resulting in

[["Fitness"], ["Fashion", "Foodie"]]
.

keyof User["userTags"][]
signifies a desire for the keys of that array of arrays: keyof UserTags[][]. As the key of an array is a number, TypeScript returns number | keyof UserTags[][] (though it should just be number).


You might have intended to obtain the keys for the UserTags enum object. Using keyof typeof UserTags will yield the union type

"FITNESS" | "FOURTWENTY_FRIENDLY" | "MEDITATION" ...
. However, this may not align with your actual requirement, as what you seek is the union of the enum values provided by UserTags.

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

The issue arises when trying to access the 'addCase' property on the type 'WritableDraft<search>' within the builder argument of extra reducers

I am a beginner when it comes to using TypeScript with Redux Toolkit and I have encountered an issue with addCase not being available on the builder callback function in my extraReducers. I haven't been able to find a similar situation online, and I s ...

Typescript conditionally mandatory arguments

In search of a way to create a function with optional parameters in TypeScript? Look no further! Imagine needing certain parameters to be optional, but if they are provided, then others become required. Take this whimsical example: type PersonInfo = { n ...

typescript add some flair to the setter function

I'm attempting to enhance a setter function within a class in the following manner: export class SearchResultSortBy{ private sortByChoice; constructor() { ...} /* getters & setters */ get sortBy() { return this.sortByCh ...

Importing node_modules in Angular2 using TypeScript

My Angular2 app started off as a simple 'hello world' project. However, I made the questionable decision to use different directory structures for my development environment and the final deployment folder on my spring backend. This difference c ...

Updating and Preserving Content in Angular

I've encountered an issue while working on a code that allows users to edit and save a paragraph on the screen. Currently, the editing functionality is working fine and the save() operation is successful. However, after saving, the edited paragraph do ...

Cypress automation script fails to trigger Knockout computed subscription

Within my setup, I have implemented two textboxes and a span to display the result. Date: <input data-bind="value: dateValue"/> Number: <input data-bind="value: dateValue"/> Result : <span data-bind="text: calculatedValue">Result Should ...

Altering or including new space variables within a custom Chakra-ui theme

Looking to customize spacing variables in a Chakra UI theme? I have successfully implemented various extensions, but changes to spacing are not being applied. const config: ThemeConfig = { initialColorMode: 'light', useSystemColorMode: false ...

Converting Celsius to Fahrenheit using AngularJS

As a beginner in programming, I am eager to create a program similar to the one shown in the image below. https://i.sstatic.net/HvLyH.png In my 'converter.component.html' file, I have written the following code: <html> <head></hea ...

Combining and grouping objects by their IDs in a JavaScript array

Information: [ { "id": "ewq123", "name": "Joshua", "order": "Pizza" }, { "id": "ewq123", "name": "Joshua", "order": ...

Download a collection of base64 images as a ZIP file in Angular 4

I am currently developing an Angular2 v4 app using Typescript and I'm looking for a solution to download multiple images (in base64 format) as a Zip file. For instance, I have a sample array like this (containing fake base64 images just for illustrat ...

Conflicting TypeScript errors arise from a clash between React version 16.14 and @types/hoist-non-react-statics 3.3.1

Currently in the process of upgrading an older project to React 16.14, as we are not yet prepared for the potential breaking changes that would come with moving up to React 17 or 18. As part of this upgrade, I am also updating redux and react-redux to ver ...

Using useState as props in typescript

Let's imagine a situation where I have a main component with two smaller components: const MainComponent = () => { const [myValue, setMyValue] = useState(false) return ( <> <ChildComponent1 value={myValue} setValue={set ...

What is the reason for a boolean extracted from a union type showing that it is not equivalent to true?

I'm facing a general understanding issue with this problem. While it seems to stem from material-ui, I suspect it's actually more of a typescript issue in general. Despite my attempts, I couldn't replicate the problem with my own types, so I ...

Array containing multiple service providers in Angular

I encountered a problem while utilizing multiple providers in my application: ERROR Error: No provider for Array! at injectionError (VM634 core.umd.js:1238) [angular] at noProviderError (VM634 core.umd.js:1276) [angular] at ReflectiveInjector_._throwOrNul ...

Encountering an HTTP parsing failure while sending XML through Angular 5's HttpClient

Struggling to access a local webservice through XML: Take a look at the code below: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'text/xml', 'Accept': 'text/xml', 'Response- ...

Guide to setting up an interface-only project (along with its dependent projects) on NPM

I'm encountering two problems with my TypeScript project. Imagine I have a interface-only TypeScript project called myproject-api. My plan is to implement the interfaces in two separate projects named myproject-impl1 and myroject-impl2. I am utilizin ...

Rx.js struggles to access historical values

Seeking assistance with retrieving the last 3 values emitted. Despite using the provided code to populate uiOrder and invoking cancelOrderItem() multiple times, I am unable to access the last 3 revisions of the order via getHistory(). Instead, I receive th ...

`Angular 9 template directives`

I am facing an issue with my Angular template that includes a ng-template. I have attempted to insert an embedded view using ngTemplateOutlet, but I keep encountering the following error: core.js:4061 ERROR Error: ExpressionChangedAfterItHasBeenCheckedEr ...

Limitations of MaterialUI Slider

Looking for a solution to distribute 350 points across 8 sliders, each with a range of 0-100 and 5 marks at 0, 25, 50, 75, and 100. With each step consuming or returning 25 points, the challenge lies in allowing users to adjust the points allocation withou ...

Leverage the power of mathematical functions within Angular to convert numbers into integers

In my Angular 7 Typescript class, I have the following setup: export class Paging { itemCount: number; pageCount: number; pageNumber: number; pageSize: number; constructor(pageNumber: number, pageSize: number, itemCount: number) { thi ...