Find a type that matches a string with any number of arguments separated by commas

Looking for a type that specifically matches strings starting with the prefix func and surrounded by any number of arguments within parentheses.

func(1, 2, 3, 4, 5)
func(1, 2, 3)
func(1, 2, 3, 4, 5, 6, 7)

Here is what I have so far:

type MyType = `func(${string})`

Answer №1

It's important to note that TypeScript types cannot be used to validate object values at runtime; for that, a regex or a validation library like zod or joi would be necessary. String literals can only be validated at compile time.

However, if TypeScript had support for recursive template literal types, creating a type as described could be straightforward:

type Param = number;
type Params = '' | `${Params}, $Paraam`
type Func = `func(${Params})`

Unfortunately, the code above results in an error due to circular reference within the Params type.

Type alias 'Params' circularly references itself.ts(2456)

As a workaround, you have to manually list out the types with an upper limit:


type N = number;
type Params = ''
  | `${N}`
  | `${N}, ${N}`
  | `${N}, ${N}, ${N}`
  | `${N}, ${N}, ${N}, ${N}`
  | `${N}, ${N}, ${N}, ${N}, ${N}`
  | `${N}, ${N}, ${N}, ${N}, ${N}, ${N}`
  | `${N}, ${N}, ${N}, ${N}, ${N}, ${N}, ${N}`

type Func = `func(${Params})`

const f: Func = 'func(1, 2, 3, 4, 5, 6, 7)'; // OK
const g: Func = 'func 1, 2, 3, 4, 5, 6, 7 '; // Error

A utility type could potentially eliminate the need for manual listing, but without support for recursive template literal types, there will still be an upper limit.

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

Utilizing an ES6 module function within a commonJS TypeScript script by importing and calling it

For our backend nodeJS (typescript) project, we need to utilize the 'parse-domain' package (version 7.0.1). However, we encountered an issue where this package is not compatible with commonJS, making it unable to be loaded using require. The work ...

Is there a deeper philosophical rationale behind choosing to use (or not use) enums in TypeScript, along with string union types?

Recently, I delved into the world of enum and const enum in Typescript, causing some confusion. I grasped that const enum gets transpiled into simple values while regular enums do not. I also recognized certain distinctions between using string union type ...

Vee-Validate: Are flags on the field value yielding undefined results? Explained with TypeScript

The documentation states that by using a flag on the value of a field, I should be able to obtain a boolean. For example: computed: { isFormDirty() { return Object.keys(this.fields).some(key => this.fields[key].dirty); } }, I am working ...

Building custom components in Ionic 4

What is the best way to integrate a newly created component in Ionic 4 after executing ionic g component myComponent? I am looking to incorporate this custom component into my home page. ...

Guide to encoding an array of objects into a URI-friendly query string using TypeScript

Just getting started with typescript and looking for some help. I have an input array structured like this: filter = [ { field : "eventId", value : "123" }, { field : "baseLocation", value : "singapore" } ] The desired format for ...

Troubleshooting issue of data-binding failure with dynamic component loader in Angular2-universal-started

I am currently utilizing the angular2-universal-starter project. While attempting to pass an object to a child component using @Input, I encountered some issues with it not functioning correctly. I have implemented a dynamic component loader to load the ...

Best practice for refreshing React UseState

Is there a more efficient way to rerender a component without using a resource-intensive script? I currently use a useState() to trigger the rerender, but it's not ideal. My current approach: const restartClick = (): void => { setDivClass(&q ...

What is the best way to obtain an attribute name that is reminiscent of Function.name?

My objective is to securely type an attribute. For example, I have an object: const identity = { address: "Jackie" }; At some point, I will rename the address key to something else, like street_address. This is how it is currently implemented ...

Utilize the value of one variable to determine access to another variable in Javascript

I am working with several boolean variables and I want to create a new variable that keeps track of the most recently changed boolean variable. This way, every time a new boolean variable is modified, I can toggle the previous one. If you have any ideas o ...

Solving the challenge of magnifying images in React without the use of any

I am working on adapting this image magnifier code for React Typescript without relying on an external library. The original Vanilla Javascript Codepen can be found here. Instead of copying and pasting the CSS into a separate file, I want to incorporate it ...

Does Angular 8 development mode implement tree-shaking?

I am curious to know if tree-shaking occurs during Angular 8 development mode. When running the following command: ng build I understand that tree-shaking happens when I use the command below: ng build --optimization=true|false ...

Instructions on invoking a function from another Material UI TypeScript component using React

In this scenario, we have two main components - the Drawer and the AppBar. The AppBar contains a menu button that is supposed to trigger an event opening the Drawer. However, implementing this functionality has proven challenging. I attempted to use the li ...

The error message "@types/d3" states that the type 'Area<X>' cannot be assigned to the type 'String'

Within a typescript class, I have a method instance... createArea = d3.area<Point>().x((d) => d.x).y0((d) => d.max).y1((d) => d.y); Although this method works fine, it is being seen as an instance field. To rectify this, I tried adding a t ...

Triggering actionsheet button clicks in Ionic 3

I need assistance with adding buttonClick functionality to actionSheet buttons in ionic 3. When a button is clicked, I want to open a modal (custom alert). Below is the code snippet: openActionSheet() { console.log('opening'); le ...

What is the best approach in Typescript to ensure type understanding when importing using require()?

Currently, I am working with TypeScript within IntelliJ. Let's say I have the following code: const functions = require('firebase-functions'); Then I proceed to use it in this manner: exports.doSomething = functions.https.onCall((data, c ...

Troubleshooting puppeteer error: "Property 'contentFrame' of null cannot be read"

I've encountered a bug while trying to request an API that I've implemented. After using one of the endpoints, it throws the following error, as shown below. Is there any way to handle this error? Error message: TypeError: Cannot read property ...

Guide to starting a typed array in Typescript

I have an array called "cart" of objects that is initially empty, but structured like this: cart:[{name:any, rate:number, qty:number, discount:number, subtotal:number}] When I attempt to add data to it like so: cart:[{name:any, rate:number, qty:number, ...

RXJS expand keeps on recursing indefinitely

After successfully uploading a file to Firebase, I implemented a recursive function to listen for GCP trigger logs. Everything seems to be working well, but I'm facing an issue where the recursive expand function never exits. Despite checking the val ...

a collection of Interface objects

I've created an interface that looks like this: export interface testInterface { value1: string; value2: string[]; SubValue: [{}] } Everything works fine as I fill an array of type testInterface, which is bound to a dropdown list. Now, ...

Angular 5 and NodeJS: Leveraging the Power of HTTP Get Requests

After working with MVC under the .NET framework for 3 years, I decided to challenge myself by taking on a MEAN stack project. However, I have reached a point where I feel I need further training or assistance. Although I have successfully implemented get a ...