Using Typescript for defining regular expressions as enum values

When making API calls from an API in typescript, I want to clarify how the response should look by using an interface. One particular value is a string that can only have specific values. Isn't this what enums are for?

The possible values are:

"Normal Goal", "Own Goal", "Penalty", "Missed Penalty", 
"Yellow Card", "Second Yellow Card", "Red Card",
"Substitution x"

where x can be any positive integer. The challenge lies in implementing this. I attempted to use Regex, like so:

enum Event {
  "Normal Goal", "Own Goal", "Penalty", "Missed Penalty", 
  "Yellow Card", "Second Yellow Card", "Red Card",
  "Substitution [1-9]\d*$"
}

Unfortunately, this approach didn't work as expected. If this method proves impossible, I may have to change the enum to a string type. Do you have any alternative suggestions for achieving this?

Answer №1

If you want to streamline your code, consider using a single regular expression that covers all possible values instead of an enum. This way, you can check the value at runtime:

const event : RegExp = /(?:^|(?<= ))(Normal Goal|Own Goal|Penalty|Missed Penalty|Yellow Card|Second Yellow Card|Red Card|Substitution [1-9]\d*$)(?:(?= )|$)/

However, if you prefer to use a type for specific literals, then you will need to elaborate on the regex in your type definition:

type MatchEvent = 
        "Normal Goal"|
        "Own Goal"|
        "Penalty"|
        "Missed Penalty"|
        "Yellow Card"|
        "Second Yellow Card"|
        "Red Card"|
        "Substitution 1"|
        "Substitution 2"|
        ...
        "Substitution 99";

Answer №2

Big shoutout to Christian for inspiring me to think outside the box and ditch the enum approach. I ended up creating my own custom type that can handle either predefined "enum strings" or a RegEx pattern.

Here's what my updated code looks like:

type Event = ("Normal Goal"|"Own Goal"|"Penalty"|"Missed Penalty"|"Yellow Card"|"Second Yellow Card"|"Red Card"|"Substitution [1-9]\d*$)(?:(?= )|"$);

interface I {
  test: Event
}

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

Steps to utilize redux in a fresh react class component

Within my App, there are two buttons - one for saving a message and another for creating a new component. import React from "react"; import { connect } from "react-redux"; import { AppState } from "./redux/store"; import { ChatState } from "./redux/chat/t ...

Determine the return value of a function based on a specific conditional parameter

Is it possible for a function with a parameter of a conditional type to return conditionally based on that parameter? Explore the concept further here I am faced with a scenario where I have a function that takes one parameter, which can either be a cust ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

Ionic has been experiencing issues with inaccurate boolean results being generated by Angular typescript

I have created a random number generator that requires the user to input a maximum and minimum value to generate a random number within that range. The application will show an error under two conditions: If either of the numbers entered is negative If t ...

Utilize an Angular HttpInterceptor to invoke a Promise

I have an angular HttpInterceptor and I am in need of invoking an encryption method that is defined as follows: private async encrypt(obj: any): Promise<string> { However, I am unsure of how to handle this within the HttpInterceptor: intercept(req ...

Is there a way to dynamically retrieve a JSON element in Typescript?

I am using a data grid throughout my application, and currently, I am retrieving the selected rowid with the following code. Here is the HTML snippet: <tbody> <tr *ngFor="let ddata of tableData.data; let i = index" (click)="setClickedRow(ddat ...

Unable to narrow down the truthiness within nested functions: TypeScript issue

When analyzing the code in the shared playground (Playground Link), the compiler is showing an error indicating that Object is possibly 'null'. Could there be any scenario where the refresh function could be called, leading to a situation where ...

Ways to differentiate between the sources of two cold Observables (not just the possible data streams they may produce)

Situation: Within my Angular application, I am using publishReplay to store and replay specific Http requests. However, I encountered an issue where I need the cached observable source to update itself and create a new cached observable with publishReplay ...

In Python, you can utilize the re.search function to find occurrences of opening and closing brackets

Could someone please clarify why my regular expression is failing to match the given input. I'm looking for a solution on how to handle square brackets in the regex pattern. >>> str = li= "a.b.\[c\]" >>> if re.search(li,st ...

Enhance Tuple in Angular Component Properties

When using React, state variables can be created like this: const SomeComponent = ({ someProp }) => { const [value, setValue] = useState<boolean>(false); } I wonder if there is a similar way to achieve the spread of a tuple within an Angular co ...

The MUI datagrid fails to display any rows even though there are clearly rows present

Today, I encountered an issue with the datagrid in Material UI. Despite having rows of data, they are not displaying properly on the screen. This problem is completely new to me as everything was working perfectly just yesterday. The only thing I did betwe ...

Ways to generate an array containing the headings from a list using typescript?

How can I extract the headers of objects in an array in TypeScript? let data = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}]; let headers = Ob ...

What are the steps to set up a dictionary with predetermined values?

My task is to create a pre-defined dictionary where the key represents a city and the value is an array of zones in that city. Here is my attempt: export const cityToZone: { [city: string]: Array<string> } = [ {city:'New York', [&apos ...

Managing errors when dealing with Observables that are being replayed and have a long lifespan

StackBlitz: https://stackblitz.com/edit/angular-ivy-s8mzka I've developed an Angular template that utilizes the `async` pipe to subscribe to an Observable. This Observable is generated by: Subscription to an NgRx Store Selector (which provides sele ...

Trouble encountered while configuring and executing Electron combined with React, Typescript, and Webpack application

I am currently in the process of migrating my Electron application from ES6 to Typescript. Despite successfully building the dll and main configurations, I encounter a SyntaxError (Unexpected token ...) when attempting to run the application. The project c ...

The conditional type in TypeScript is malfunctioning

Upon finishing an article discussing conditional types in TypeScript located at: I have attempted to implement a conditional type in the following function: function convertToIsoString<T extends number|undefined>( timestamp:T ): T extends number ...

Traversing a sequence of method calls within a Promise object (as the return type)

In software development, there is a classic technique where a method returns the result of another method call: method1(): ObjectX { if( condition1 ) return method2(); return undefined // or some default value; } method2(): ObjectX { let r ...

Guide to slicing strings specifically with numerical characters at the end

I've encountered a challenge. I need to slice the last two characters in a string, but only for strings that contain numbers. I attempted using "nome": element.nome.slice(0,-2) and now I require some sort of validation. However, figuring out how to do ...

Circular structure error occurred when attempting to convert an object to JSON, starting at an object constructed with the constructor 'Object'

I am facing an issue where I need to update a Medico from the collection, and I have successfully destructured the data of the Medico's name and email. Additionally, I have obtained the ID of the assigned hospital. However, I am having trouble sendin ...

"Utilizing generic types with the 'extends' keyword to input arguments into a function that requires a more specific

I recently tried out the TypeScript playground and came across a puzzling issue that I can't seem to wrap my head around. Below is the code snippet: type Foo = { t: string; } type Bar = string | { date: Date; list: string; } function te ...