What is the process for transforming every data type within an array?

My problem involves handling various types of data

type ParseMustaches<T extends string[], U extends Record<string, string> = {}> = 
  T extends `{{${infer U}}}` 
    ? Record<U, string> 
    : never

type Test = ParseMustaches<["{{sitename}}", "{{user}}"]>

// The expected result for Test is { sitename: string, user: string }

I need assistance in creating an object with required keys, where the keys are inferred values and the values are strings. How can I accomplish this? Check out the playground using the TS version I am utilizing and here is the link to the PR that enables inferring strings

Answer №1

The reason for this behavior is that T is a tuple or array, so it does not expand the pattern. To properly check, you should test the individual items in the tuple:

type ExtractMustaches<T extends string[]> = 
  T[number] extends `{{${infer U}}}` 
    ? Record<U, string> 
    : never

Try it out here

Answer №2

If you find yourself limited in the ways you can modify the ParseMustaches function, here is a workaround that will give you the same output:

type ParseMustaches<U extends keyof any> = Record<U, string>

type Example = ParseMustaches<'sitename' | 'user'>


// expected result
// type Example = {
//     sitename: string;
//     user: string;
// }

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

Using immer JS to update a nested value has been successfully completed

What is the most efficient way to recursively change a value using a recursive function call in a Produce of Immer? The WhatsappState represents the general reducer type, with Message being the message structure for the application/db. type WhatsappState = ...

Do not display large numbers within an HTML card

I have https://i.sstatic.net/DkowD.png this card here and displaying dynamic data inside it. The number is quite large, so I would like it to appear as 0.600000+. If a user hovers over the number, a tooltip should display the full number. How can I achieve ...

ng-select search functionality failing to display any matches

Currently, I am encountering an issue with the ng-select functionality in my Angular CLI version 11.2.8 project. Despite using ng-select version 7.3 and ensuring compatibility with the Angular CLI version, the search functionality within the select eleme ...

The function is receiving an empty array of objects

This code is for an Ionic app written in typescript: let fileNames: any[] = []; fileNames = this.getFileNames("wildlife"); console.log("file names:", fileNames); this.displayFiles(fileNames); The output shows a strange result, as even though there ar ...

Node.js is raising an error because it cannot locate the specified module, even though the path

Currently in the process of developing my own npm package, I decided to create a separate project for testing purposes. This package is being built in typescript and consists of a main file along with several additional module files. In the main file, I ha ...

What exactly does "context" refer to in the context of TypeScript and React when using getServerSideProps?

As a beginner in coding, I have a question regarding a specific syntax I recently encountered. I am confused about this particular line of code and couldn't find any helpful explanations online: export async function getServerSideProps(context: GetSer ...

Tidying up following the execution of an asynchronous function in useEffect

Recently, I've been facing a challenge while migrating a React project to TypeScript. Specifically, I'm having trouble with typing out a particular function and its corresponding useEffect. My understanding is that the registerListener function s ...

RxJS emits an array of strings with a one second interval between each emission

Currently, my code is set up to transform an Observable<string[]> into an Observable<string>, emitting the values one second apart from each other. It's like a message ticker on a website. Here's how it works at the moment: const ...

The parameter 'unknown[]' cannot be assigned to the type 'OperatorFunction'

component.ts initialize() method explains The error message says 'Argument of type 'unknown[]' is not assignable to parameter of type 'OperatorFunction<unknown[], unknown>'. Type 'unknown[]' does not match the si ...

Encountering a WriteableDraft error in Redux when using Type Definitions in TypeScript

I'm facing a type Error that's confusing me This is the state type: export type Foo = { animals: { dogs?: Dogs[], cats?: Cats[], fishs?: Fishs[] }, animalQueue: (Dogs | Cats | Fishs)[] } Now, in a reducer I&a ...

How can I best declare a reactive variable without a value in Vue 3 using TypeScript?

Is there a way to initialize a reactive variable without assigning it a value initially? After trying various methods, I found that using null as the initial value doesn't seem to work: const workspaceReact = reactive(null) // incorrect! Cannot pass n ...

Azure functions encountered an issue: TypeError - it seems that the connection.query function is not recognized

Having a slight issue with my Azure function that is supposed to retrieve all data from a SQL table. The connection to the database is successful, but whenever I attempt to run the get request, it results in an error Exception: TypeError: connection.query ...

Utilize Typescript compiler to identify mistakes during object property access using square brackets

Is it possible to configure the Typescript compiler to identify errors when accessing object properties using square brackets? I have inherited a codebase where object property access is predominantly done with square brackets (obj['myProp'] ins ...

Leveraging Typescript Definitions Files from Definitely Typed with an Outdated Typescript Version

I've been struggling with integrating third party React component libraries into my project that uses Typescript 1.8.10 along with React and Redux. Specifically, I've been attempting to use React Date Picker, but have encountered issues due to th ...

When the route changes, routerCanReuse and routerOnReuse are not invoked

I am currently exploring the functionalities of Angular2's Router, specifically focusing on OnReuse and CanReuse. I have followed the documentation provided here, but I seem to be encountering difficulties in getting the methods to trigger when the ro ...

Getting the value of the chosen option from one component and passing it to another component in Angular 8

How can I pass the selected option value from the login component to the home component without using local storage? When an option is selected in the login component, I want that value to be displayed in the home component. Below is the code snippet: Lo ...

Issue during Docker build: npm WARN EBADENGINE Detected unsupported engine version

Currently, I am constructing an image based on mcr.microsoft.com/devcontainers/python:0-3.11-bullseye. In my docker file, I have included the following commands towards the end: RUN apt-get update && apt-get install -y nodejs npm RUN npm install np ...

In the latest version of Expo SDK 37, the update to [email protected] has caused a malfunction in the onShouldStartLoadWithRequest feature when handling unknown deeplinks

After updating to Expo SDK 37, my original code that was previously functioning started encountering issues with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7c6b6f6d7a23606f7a67786b23796b6c78667f79627a">[email prot ...

Encountering multiple error messages from Protractor @types

Lately, I've been using the Angular2 Webpack Starter created by AngularClass and I've started encountering some perplexing errors with Protractor. When trying to build, these errors pop up: Module 'webdriver' has no exported member &ap ...

What factors should I consider when determining whether to include @types/* in the `dependencies` or `devDependencies` section?

Currently using TypeScript 2 in my project, I am looking to incorporate a JavaScript library along with its typings. While I know I can easily install the types using npm install @types/some-library, I am uncertain whether to use --save or --save-dev. The ...