Is it possible to dynamically check values in TypeScript?

[Summary] I am looking to dynamically expand my type in TypeScript based on an initial set of values. I want to avoid managing separate arrays/types and instead extend all strings in my type with '_max'.

type ExtendedValueTypes = 'money' | 'land' | 'money_max' | 'land_max';
// dynamically from
type ValueTypes = 'money' | 'land';

I have a list of values

const values = ['money', 'land'] as const;
type ValueTypes = typeof values[number];
// equals ValueTypes = 'money' | 'land';

Now I want to dynamically extend my type to equal

type ExtendedValueTypes = 'money' | 'money_max' | 'land' | 'land_max';

To achieve this, I need a type declaration that automatically appends '_max' to all the strings in my type definition.

const check = (type: ValueTypes) => 'some return'

//works
check('money');

// does not work but should
check('money_max')

Answer №1

If you want to manipulate string literal types, you can utilize template literal types in the following manner:

type ExtendedValueTypes = ValueTypes | `${ValueTypes}_max`
// type ExtendedValueTypes = ValueTypes | "money_max" | "land_max"


const check = (type: ExtendedValueTypes) => 'some return'

//works
check('money');

//works
check('money_max');

Link to Playground with code example

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

I am configuring Jest in my Vite and TypeScript-powered React project

I am having trouble with the relative path of the file I imported in App.test.tsx. It keeps showing me this error message: Cannot find module '@/components/items/card.tsx' from 'src/__tests__/App.test.tsx' Below is the code snippet: // ...

Is there a way to insert data from one table into a MySQL Table in Drizzle and update the entry if it already exists?

My goal is to utilize Drizzle for inserting data into a table and updating it if the key already exists. In MySQL, the code would look like this: INSERT INTO myTable1(field1,field2,field3,field4) SELECT fieldOne,fieldTwo,fieldThree,fieldFour FROM myTable2 ...

Configuring NextUI with Next.js and TypeScript - CssBaseline component not found in @nextui-org/react package

Struggling to find reliable resources for installing Next.js and NextUI with the latest versions? The most helpful guide I found was this one, but not everything aligns perfectly. The guide instructs me to import CssBaseline like this: import { CssBaselin ...

How to Efficiently Remove Array Elements by Index in Typescript

What is the best way to remove an item by its index using Typescript? For example: let myArray = ['apple', 'banana', 'cherry', 'date']; // How can I delete the item at index 2? ...

Unleash the power of Typescript and Node to create detailed REST API documentation!

Is it possible to generate REST API documentation using https://github.com/TypeStrong/typedoc similar to what can be done with ? I would appreciate any recommendations on leveraging TypeScript types for creating REST API documentation (specifically within ...

Exploring the Angular TypeScript Method for Rendering Nested Objects in an Array

Within this array, I have a collection of objects that contain properties for model and color. My goal is to present these objects in a table format, with individual access to the color values. grp = [ {model: "CF650-3C", color: {Orange: 3, Black ...

After successfully logging in, the deployed server encounters an Error 503 and shuts down. However, on the development environment, everything runs smoothly as

I am currently in the process of developing an application using NET 6 LTS and Angular 14. Everything runs smoothly on my development environment with IIS express. However, once I deploy the application (release version) on Windows 2019 with IIS 10, I enco ...

Ensure that child components' property types are enforced in TypeScript

I am trying to enforce the type of a property in a child component. I expected the code below not to compile because Child's property name is not correctly typed inside Parent within the app. However, there is no compiler warning displayed. Is there ...

Instructions on how to post an array by its ID when the value changes in the form, correspond with the ID

Whenever I change the value in the radio button within a form popup, I want to trigger this action. Below is the corresponding HTML code: <ng-container cdkColumnDef="injected"> <mat-header-cell *cdkHeaderCellD ...

Issue with Angular data display in template

My Ionic app with Angular is fetching data in the constructor, but I am facing difficulties displaying it in the HTML. Code component receiver: any; constructor( //.... ) { // get receiver data const receiverData = this.activatedRoute.snapsho ...

Is it feasible to bring in a Typescript file into an active ts-node REPL session?

I want to experiment with some Typescript code that I have written. Currently, I usually run ts-node my-file-name.ts to test it out. But I am interested in making this process more interactive, similar to the Python REPL where you can import modules and ...

The imported variables are of a union type

In my nextjs project, I developed a customized hook to determine if a specific container is within the viewport using the intersection observer. Here's the code for the custom hook: import { useEffect, useRef, useState } from 'react'; cons ...

Looking to create universal React component wrappers?

I am working with a set of functional components that share a common set of properties, for example: const A = ({ x, y, z }) = {...} const B = ({ x, y, z }) = {...} For these components, I have predefined configurations: const styles { A: { ty ...

Could you please explain the significance of /** @docs-private */ in Angular's TypeScript codebase?

After browsing through the @angular/cdk code on GitHub, I came across a puzzling "docs-private" comment. Can anyone explain its significance to me? Link to Code * In this base class for CdkHeaderRowDef and CdkRowDef, the columns inputs are checked for ...

What is preventing the dependency injection of AuthHttp (angular2-jwt) into a component?

UPDATE: Success! Problem Solved After much trial and error, I finally discovered the solution to my issue. It turned out that the problem lied in a simple configuration mistake. To rectify this, I made changes to both my package.json (dependencies section ...

In JavaScript, loop through an array of arrays and combine them using the concat

If I have an array like [["a", "b"], ["c", "d"]], is there a way to iterate, reduce, map, or join this array in order to get the desired output of ["ac", "ad", "bc", "bd"]? What if the array is structured as [["a", "b"], ["c", "d"], ["e", "f"]]; how can we ...

Is it possible to both break down a function parameter and maintain a named reference to it at the same time?

When working with stateless functional components in React, it is common to destructure the props object right away. Like this: export function MyCompoment({ title, foo, bar }) { return <div> title: {title}, ...</div> } Now ...

Is there a way to add an event listener to dynamically generated HTML using the v-html directive?

I have a string variable named log.htmlContent that contains some HTML content. This variable is passed into a div to be displayed using v-html. The particular div will only be displayed if log.htmlContent includes an img tag (http: will only be present in ...

What method can be used to verify if a username exists within Angular data?

We want to display online users on a webpage by checking if they are currently active. The current code logs all online users in the console, but we need to show this visually on the page. public isOnline: boolean = false; ... ... ngOnInit() { ...

React-Redux: Unable to access the 'closed' property as it is undefined

Encountered a problem when using dispatch() in React-Redux. Specifically, the action below: export const fetchMetrics = () => { dispatch(fetchMetricsBegin); APIService.get('/dashboard/info/') .then((response) => { ...