What is the best approach to efficiently generate an array that strictly follows a specified Union type without the need for manual duplication?

Having the specific NameUnion type, it is important for consistency that I define it once and later on check if an array contains an element from the NameUnion type.

type NameUnion =
  // Home && login
  | 'email'
  | 'newEmail'
  | 'password'
  | 'passwordConfirm'
  | 'deleteAccountPassword'

if(['email','newEmail','password','passwordConfirm','deleteAccountPassword'].includes(name)){
// do somthing
}

Answer №1

In this particular instance, the NameUnion represents the type, while the nameArray embodies an array of that specific type. It serves as a tool for the inclusion check you desire. By employing the doSomething function, you can assess whether a parameter of type NameUnion is present in the nameArray.

This recommended strategy entails the following:

type NameUnion =
  | 'email'
  | 'newEmail'
  | 'password'
  | 'passwordConfirm'
  | 'deleteAccountPassword';

const nameArray: NameUnion[] = ['email', 'newEmail', 'password', 'passwordConfirm', 'deleteAccountPassword'];

function doSomething(name: NameUnion): void {
  if(nameArray.includes(name)){
    // Implement actions here
    console.log(`name is in the NameUnion: ${name}`);
  } else {
    console.log(`name is NOT in the NameUnion: ${name}`);
  }
}

// Test Cases
doSomething('email');  // Expected output: "name is in the NameUnion: email"
doSomething('other');  // Expected output: "name is NOT in the NameUnion: other"

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

Tips for modifying a TypeScript object by its key value?

I am facing an issue where I have the key's value as a string and need to update the object based on this key value. Is there a method in TypeScript that can help me achieve this? I attempted to use the <object_name>[key] = value method but unf ...

Loading an external javascript file dynamically within an Angular component

Currently, I'm in the process of developing an Angular application with Angular 4 and CLI. One of my challenges is integrating the SkyScanner search widget into a specific component. For reference, you can check out this Skyscanner Widget Example. T ...

Press the key to navigate to a different page

I have an input field for a search box. I want it so that when I enter my search query and press enter, the page navigates to another page with the value of the input included in the URL as a query string. How can I achieve this functionality? Thank you ...

Combining Firebase analytics with an Ionic 3 application using the Ionic Native plugin

I placed the GoogleService-Info.plist file at the root of the app folder, not in the platforms/ios/ directory. When I tried to build the app in Xcode, an error occurred in the following file: FirebaseAnalyticsPlugin.m: [FIROptions defaultOptions].deepLin ...

Preventing text from wrapping in a TypeScript-generated form: Tips and tricks

I’m currently working on a ReactJS project and my objective is simple: I want all three <FormItem> components to be displayed in a single line without wrapping. However, I am facing the following output: https://i.stack.imgur.com/mxiIE.png Within ...

Using TypeOrm QueryBuilder to establish multiple relations with a single table

Thank you for taking the time to read and offer your assistance! I am facing a specific issue with my "Offer" entity where it has multiple relations to "User". The code snippet below illustrates these relationships: @ManyToOne(() => User, (user) => ...

Utilizing Interface Merging: Determining the Appropriate Instance Type for Field Types

I am in need of writing a definition file for an external library. I have augmented a class using interface merging and there are situations where a field of the library class is of the same type as the instance itself. Here is a snippet of demo code: // ...

Enhancing RTK Query: Efficiently Filtering Query Results in Separate Components

I am currently working on a Todo application using Nextjs 13 with various tools such as app directory, prisma, redux toolkit, shadcnui, and clerk. Within my app, I have implemented two key components - TodoList and Filter. The TodoList component is respons ...

Tips for restricting custom number types based on if conditions in TypeScript

Programming Digits type NumType = 1 | 2 | 3 | 4 | 5; function numFunc(number: NumType) { console.log("Number selected: ", number); } const randomNumber = Math.floor(Math.random() * 10); if (0 < randomNumber && randomNumber < 6 ...

One inventive method for tagging various strings within Typescript Template Literals

As TypeScript 4.1 was released, many developers have been exploring ways to strictly type strings with predetermined patterns. I recently found a good solution for date strings, but now I'm tackling the challenge of Hex color codes. The simple approa ...

Stage setting timeout for the playwright

const test = defaultTest.extend({ audit: async ({ page }) => { await page.screenshot({ path: 'e2e/test.png' }); console.info('audit done!'); }, }); // ...more code test.only('audit', async ({ page, mount, audi ...

Exploring the implementation of TypeScript Generics in react-hook-form interfaces

This is the code I have: export interface PatientFormInputs { patientId: string; firstName: string; lastName: string; email: string; day: string; month: string; year: string; } In a React component: const { control, register, h ...

Customizing the appearance of antd Button using emotion and typescript

I've been attempting to customize an antd Button component using emotion in TypeScript, but I encountered an error when trying to implement the styled Button. The error message I received was: Type '{ children: never[]; }' is not assignab ...

Issue with Angular2 - namespace webdriver not detected during npm installation

Upon restarting my Angular2 project, I ran the npm install command and encountered this error message: node_modules/protractor/built/browser.d.ts(258,37): error TS2503: Cannot find namespace 'webdriver' Does anyone have insight into the origin ...

You cannot use Angular 5 to send a post request with a token that has been retrieved

Hello, I'm facing an issue with making a post request in Angular 5. The token I retrieve seems correct as it works fine when tested with Postman. Can someone provide me with a hint or suggestion on what could be going wrong? AuthService.ts getProfi ...

Using the Yammer REST API to post messages.json with a line break

I'm having trouble adding line breaks to my posts on Yammer through the REST API. While I can include line breaks when posting directly on Yammer, I can't seem to achieve the same result programmatically. It appears that Yammer may be escaping th ...

Sort and incorporate elements by multiple strings present in an array

Looking to filter and include strings in an array by matching them with items in another array? Here is a sample code snippet that filters based on a single string: const filteredString = `${this.filter}`.toLowerCase(); this.filteredCampaigns = this. ...

"Extra loader required to manage output from these loaders." error encountered in React and Typescript

After successfully writing package 1 in Typescript and running mocha tests, I confidently pushed the code to a git provider. I then proceeded to pull the code via npm into package 2. However, when attempting to run React with Typescript on package 2, I enc ...

Unable to get the Angular Formly select option to bind

I'm currently working on binding formly select type options with the following code: fieldGroup: [ { key: 'TimeOffTypeID', type: 'select', className: 'flex-40 padding-10', templateOptions ...

When attempting to parse a file name using a regular expression in TypeScript (or even plain Node.js), the unexpected outcome is a

Looking to extract language information from a filename? Check out this simple construct: The structure of my language.ts model is as follows: export interface Language { language?: string; region?: string; } The function designed for parsing the fi ...