Conditionally typing in TypeScript to check if a string contains a specific value

Looking to create a function that takes a string as input and determines whether it contains '[]' or not. If it does, the function should return a list, otherwise an object. This is what I have so far:

function customFunction<T = any>(input: string): typeof input extends `${any}[]${any}` ? Array<T> : T {
  if (input.includes('[]')) {
    return [] as T[]
  }
  return {} as T
}

Unfortunately, the function only returns a string instead of the expected type.

I am using TypeScript version 4.3.2. Can anyone assist me with this issue?

Answer №1

Using type parameters is the only way to achieve this, as real function parameters won't work:

function customFunction<S extends string, T = any>(): S extends `${infer A}[]${infer B}` ? Array<T> : T {

}
const result1 = customFunction<'a[]b'>();
const result2 = customFunction<'ab'>();

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

Storing the compiled TypeScript file in the source file's directory with the TypeScript compiler

I am in need of assistance with compiling TypeScript files (ts) into JavaScript files (js) and mapping files (js.map) all within the same directory as the source file. I have attempted to configure this in my tsconfig.json file using: { "compilerOption ...

What is the reason for the truth value of `type a = {} extends {a?:number}? true:false;`?

Why is type a = {} extends {a?:number}? true:false; evaluated as true, while type b = {a?:number} extends {}? true:false; is also true! It seems like the empty object {} acts as a supertype that can extend other types. This raises some questions about ...

Angular 2 Login Component Featuring Customizable Templates

Currently, I have set up an AppModule with a variety of components, including the AppComponent which serves as the template component with the router-outlet directive. I am looking to create an AuthModule that includes its own template AuthComponent situa ...

Generate md-card components in real-time using data fetched from an API

I have a scenario where I make an API call to fetch user profiles, and I want to generate Angular Material Design md-cards dynamically for each profile. The number of profiles retrieved can vary, hence the need for dynamic card creation. Below is the comp ...

Learn how to use JavaScript to parse binary files

Is there a way to interpret this binary data below? Binary2 { sub_type: 0, buffer: Buffer(16) [ 12, 15, 64, 88, 174, 93, 16, 250, 162, 5, 122, 223, 16, 98, 207, 68 ], position: 16 } I've attempted different methods like using ...

Dependency mismatch in main package.json and sub package.json

Imagine you have a project structure in Typescript set up as follows: root/ api/ package.json web/ package.json ... package.json In the main package.json file located in the root directory, Typescript is installed as a dependency to make ...

Guide on categorizing MUI icon types

My current code snippet is as follows: type MenuItem = { key: string; order: number; text: string; icon: typeof SvgIcon; }; However, when I attempt to use it in my JSX like this: <List> {MENU.map((menuItem: MenuItem) => ( ...

In the Angular Google Maps API, is it possible to update the attributes of <agm-marker> directly within the TypeScript code?

Currently, I am fetching markers from the database and displaying them on a map using Angular Google Maps (AGM) by utilizing the <agm-marker> tag. In my code snippet below, you can see how I fetch and store the markers in an array named markers in t ...

The most suitable TypeScript type for a screen being utilized again in react-navigation v5

When it comes to typing screens under react-navigation v5, I usually follow a simple pattern: // Params definition type RouteParamsList = { Screen1: { paramA: number } Screen2: undefined } // Screen1 type Props = StackScreenProps<R ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

What is the best way to represent the concept of "having at least one existing property and not having any additional properties" using a mapped type?

Apologies for the slightly lengthy title. Consider the following type: type A = { foo: string; bar: number; baz: boolean; } I want to define a new "partial" type B type B = Partial<A> where B must have at least one property of A and on ...

Tips for effectively invoking an API within a Next.js application

I've been exploring the most effective method for calling an external API within a Next.js application recently. Given my experience in developing MERN stack applications, I typically rely on axios for handling API requests and utilize it within a use ...

Webpack bundling, however, encountering issues with resolving TypeScript from the node_modules package

Hey everyone, I've been exploring various approaches to tackle this issue. We are working with two folders within a makeshift mono-repo structure (without using yarn workspace). One folder is named Mgt-Shared and the other is Server. We have set up a ...

When attempting to utilize yarn link, I receive an error message indicating that the other folder is not recognized as a module

After successfully running "yarn link," I encountered an issue when attempting to use it in a different project. The error message displayed was ../../.tsx is not a module. What could be causing this problem? const App: React.FC = () => { const [op ...

The specified property cannot be found on the Window type and the globalThis typeof

I encountered an error in my Electron-React-Typescript app that reads: Property 'api' does not exist on type 'Window & typeof globalThis'. window.api.send('open-type-A-window', ''); The issue seems to be related ...

How can I convert a MongoDB document into a DTO in NestJS?

I'm currently working with a data layer that interacts with a MongoDB database. My goal is to only handle MongoDB documents in this layer without exposing the implementation details to my services. My current approach involves the following code: // ...

How can I search multiple columns in Supabase using JavaScript for full text search functionality?

I've experimented with various symbols in an attempt to separate columns, such as ||, |, &&, and & with different spacing variations. For example .textSearch("username, title, description", "..."); .textSearch("username|title|description", "..."); U ...

formik connects props that are lacking certain properties

Trying to figure out a way to simplify the process of declaring all the properties of formik in my Props when using connect(). The error message I keep encountering is: Type '{ entry: Entry; }' is missing the following properties from type &apos ...

ERROR UnhandledTypeError: Unable to access attributes of null (attempting to retrieve 'pipe')

When I include "{ observe: 'response' }" in my request, why do I encounter an error (ERROR TypeError: Cannot read properties of undefined (reading 'pipe'))? This is to retrieve all headers. let answer = this.http.post<ResponseLog ...

What could be causing me to consistently receive a 0 value despite my collection having content stored within it?

How can I retrieve the value of dropVolume and use it in another method after executing my getAllDropsVolumePerDate(date) function? Each time I try to access dropVolume, it returns a value of 0. dropVolume = 0; getAllDropsVolumePerDate(date: string) { ...