TS function that determines conditional type based on payload

Can the type be determined based on a payload function?

For example:

export const myFunction = (
  findAll: boolean
) => {
  const finders: { key: if findAll is true, then VueWrapper<T>[] else VueWrapper<T> } = {}
})

In this case, I aim to alter the finders type to an Array if the findAll condition is true

Answer №1

Using Conditional Types makes it achievable.

type FindOrFindAllResult<TElement, TFindAll extends boolean>
  = TFindAll extends true
    ? TElement[]
    : TElement

const customFunction = <T, TFindAll extends boolean = boolean>(
  findAll: TFindAll
):FindOrFindAllResult<VueWrapper<T>, TFindAll> => {
  if (findAll) {
    return [] // implement your function that returns an array here
  }
  else {
    return null // implement your function that returns a single element here
  }
}


const arrayOutput = customFunction(true) // arrayOutput has type VueWrapper<T>[]
const elementOutput  = customFunction(false) // elementOutput has type VueWrapper<T>

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

Dealing with the response from Angular HttpClient.post as a string

I've come across several examples on the web that look like this: createArticle(article: Article): Observable<Article> { return this.http.post<Article>(this.url, article); } These examples all assume that the web API's response ...

The element Component is not recognized even after importing the module and applying the CUSTOM_ELEMENTS_SCHEMA schema

Recently, I integrated PinchZoom into my Angular 6 project as a node module called ngx-pinch-zoom. It's important to mention that my project is also based on Ionic 4. Within my app.module.ts file, I imported the PinchZoomModule and included CUSTOM_EL ...

Import Firebase User in Typescript v8 definition

In the previous versions of Firebase, I used to import the Typescript definition of the User like this: import {User} from 'firebase'; However, with the introduction of v8, this import no longer works and gives the following error message: Mod ...

Executing an infinite loop can occur when employing an NgRx call to dispatch an action within an Angular router

Story: Greetings to all! As a newcomer to using the NgRx library, I have encountered an issue in my Angular project where I am utilizing a router guard to prevent unauthorized users from accessing certain parts of the website. My approach involves callin ...

Guide to activating the submit button when a radio button is selected

Here is the code snippet for an edit form <form [formGroup]="editForm" (ngSubmit)="saveUser()" novalidate> <div class="form-group"> <label class="block">Gender</label> <div class="clip-radio radio-primary"> &l ...

Is there a way to programmatically trigger a CodeAction from a VSCode extension?

Can I trigger another extension's code action programmatically from my VSCode extension? Specifically, I want to execute the resolveCodeAction of the code action provider before running it, similar to how VSCode handles Quick Fixes. Most resources su ...

Utilize the provider within the decorator function

Essentially, the challenge I am facing is passing an authService to the "verifyClient" function within the @WebSocketGateway decorator. Here is how it should look: @WebSocketGateway({ transports: ['websocket'], verifyClient: (info: { req: Inc ...

Losing scope of "this" when accessing an Angular2 app through the window

My Angular2 app has exposed certain methods to code running outside of ng2. However, the issue arises when calling these methods outside of ng2 as the context of this is different compared to when called inside. Take a look at this link to see what exactl ...

Failure in retrieving values from AngularFire2 Subscribe

I am encountering an issue with the code in my authService constructor( private afAuth: AngularFireAuth, private db: AngularFireDatabase, private router: Router ) { this.authState = afAuth.authState; this.authState.subscribe((use ...

Triggering the detection of changes even when the value linked to remains the same

I'm facing an issue with a component that is supposed to react to changes in input controls by reformatting the input and removing certain characters. If the removed character corresponds to the previous value, the component fails to detect any change ...

Tips for accessing a variable from a Global service in Ionic

I am currently working on developing an app using Ionic but experiencing some difficulties. I encountered an issue while trying to access a variable from a global service when it is imported to another page. Here is an example of the Global service (backen ...

Sharing an object with a child component in Angular 2

After receiving data from a subscription, I am encountering an issue where my data is not binding to the local variable as expected. The scenario involves two components and a service. The parent component triggers a method in the service to perform an HT ...

How to load a PFX certificate from a file in NodeJS

For my current project involving Node.JS and TypeScript, one of the key requirements is to encrypt the payload body using a PFX certificate read from a .pfx file. The certificate I have is named cert1.pfx, and my code necessitates utilizing this certifica ...

Adding a Third-Party JavaScript Plugin to Angular 7

I've been attempting to integrate the read-excel-file JavaScript plugin into my Angular 7 project. Despite following all the methods recommended on various websites, I have yet to succeed. Could anyone provide a better solution? declare var readXlsx ...

I'm facing difficulty transferring information to another component

I'm currently using Next.js with TypeScript and Material UI. I have created a component called MyOrders and I am trying to pass data from MyOrders to MyOrderItem. However, I am encountering an issue where I am unable to pass the data to MyOrderItem. ...

The customer's status cannot be determined

I've encountered an issue with my TypeScript code that includes a simple if-else logic. endDate: String = ''; customerStatus: String; this.endDate = this.sampleData.customerStartDate; if (this.endDate == null) { this.customerStatus = ' ...

Splitting code is not being done through React's lazy import and the use of Webpack

//webpack development configuration const common = require("./webpack.common"); const merge = require("webpack-merge"); const globImporter = require('node-sass-glob-importer'); module.exports = merge(common, { mode: "development", modul ...

Error in Angular 2.0 final version: Unable to access the 'injector' property of null object

Upon transitioning from Angular 2 RC5 to 2.0 Final, I've encountered some errors while running my tests. It's puzzling me as to what could be causing this issue. TypeError: Cannot read property 'injector' of null at TestBed._create ...

What is the process for importing a JSON file into a TypeScript script?

Currently, I am utilizing TypeScript in combination with RequireJS. In general, the AMD modules are being generated flawlessly. However, I have encountered a roadblock when it comes to loading JSON or any other type of text through RequireJS. define(["jso ...

Configuring Stylelint in a NextJS project using Emotionjs

I recently encountered an issue while trying to integrate Stylelint into a new NextJS Typescript project with EmotionJS. Many rules were not working in my styles files, and the only error I could identify was Unknown word CssSyntaxError. This particular U ...