Is it feasible to conditionally set a function parameter as optional?

type TestType<A> = [A] extends [never] ? void : A

class Singleton<T, A> {
    private ClassRef: (new (...args: A[]) => T)
    private args: TestType<A>
    private _instance?: T

    constructor(ClassRef: (new (...args: A[]) => T), args: TestType<A>) {
        this.ClassRef = ClassRef
        this.args = args
    }

    public get instance() {
        if (!this._instance) {
            this._instance = new this.ClassRef(this.args as A)
        }

        return this._instance
    }
}

class Empty {}

const test = new Singleton(Empty)

If I specify

type TestType<A> = void

The compiler does not show any errors. However, when I do it conditionally, I encounter an error saying "Expected 2 arguments, but got 1."

Answer №1

To enhance the program, I recommend substituting the argument with a variadic tuple type. When A is of type never, the outcome for TestType will be an empty tuple. On the other hand, if not, TestType will result in a tuple containing a single element that holds A.

type TestType<A> = [A] extends [never] ? [] : [args: A]

/* ... */

constructor(ClassRef: (new (...args: A[]) => T), ...args: TestType<A>) {
    this.ClassRef = ClassRef
    this.args = args
}

Below are some test scenarios:

class Empty {}
class NotEmpty {
  constructor(arg: string) {}
}

const test1 = new Singleton(Empty)
const test2 = new Singleton(NotEmpty) 
//                          ^^^^^^^^ Error: Arguments for the rest 
//                                   parameter 'args' were not provided
const test3 = new Singleton(NotEmpty, "abc")

Playground

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

What is the process for recording information using a static method in TypeScript within a class?

For my school project, I'm struggling to retrieve the names from a class using a method. One class creates monsters and another extends it. abstract class genMonster { constructor( public id: string, public name: string, public weaknesse ...

What steps can be taken to resolve the Angular error stating that the property 'bankCode' is not found on type 'User' while attempting to bind it to ng model?

I'm encountering an issue with my application involving fetching values from MongoDB and displaying them in an Angular table. I've created a user class with properties like name and password, but I keep getting errors saying that the property doe ...

Enhance User Experience - Automatically highlight the first element in Prime NG Menu when activated

I have been working on transitioning the focus from the PrimeNG menu to the first element in the list when the menu is toggled. Here is what I've come up with: In my template, I added: <p-menu appendTo="body" #menu [popup]="true&quo ...

Cloud Formation from CDK doesn't pause for addDependency to finish

I'm currently in the process of building a CDK stack and I am fairly new to CDK. My goal is to create a Simple Email Service (SES) ConfigurationSet followed by an EmailIdentity. The issue I encountered is that the creation of the EmailIdentity fails d ...

Arrow functions do not function properly with Typescript decorators

I've created a typescript decorator factory that logs the total time taken to execute a function, along with the actual function execution results and parameters passed to the decorator. For example: export function performanceLog(...args: any[]) { ...

DxDataGrid: Implementing a comprehensive validation system for multiple edit fields

I'm currently working with a DxDataGrid within an Angular Application. Within this particular application, I have the need to input four dates. I've implemented validation rules that work well for each individual field. However, my challenge aris ...

What is the best way to arrange an array of objects in a descending order in Angular?

private sumArray : any = []; private sortedArray : any = []; private arr1 =['3','2','1']; private arr2 = ['5','7','9','8']; constructor(){} ngOnInit(){ this.sumArray = ...

What is the best way to choose an element within a component's template?

Is there a way to access an element that is defined in a component template? While Polymer has the $ and $$ to make this task simple, I am curious about how it can be done in Angular. Consider the example provided in the tutorial: import {Component} from ...

developing TypeScript classes in individual files and integrating them into Angular 2 components

We are currently putting together a new App using Angular2 and typescript. Is there a more organized method for defining all the classes and interfaces in separate files and then referencing them within angular2 components? import {Component, OnInit, Pi ...

Accessing information from RESTful Web Service with Angular 2's Http functionality

I am currently working on retrieving data from a RESTful web service using Angular 2 Http. Initially, I inject the service into the constructor of the client component class: constructor (private _myService: MyService, private route: Activat ...

Is there a way to reset useQuery cache from a different component?

I am facing an issue with my parent component attempting to invalidate the query cache of a child component: const Child = () => { const { data } = useQuery('queryKey', () => fetch('something')) return <Text>{data}& ...

Too many open files error encountered in Watchpack (watcher) - NextJS

Encountering an issue with watchpack resulting in the error messages shown above while running a next app using next dev. The error message is displayed continuously on the screen as follows: Watchpack Error (watcher): Error: EMFILE: too many open files, w ...

The error message "TypeError: 'results.length' is not an object" occurred within the Search Component during evaluation

Having trouble with a search feature that is supposed to display results from /api/nextSearch.tsx. However, whenever I input a query into the search box, I keep getting the error message TypeError: undefined is not an object (evaluating 'results.lengt ...

What is the best way to restrict the key of an object type to only be within a specific union in TypeScript?

I need to create a set of server types in a union like this: type Union = 'A' | 'B' | 'C'; After that, I want to define an object type where the keys are limited to only certain options from this Union: // Use only 'A&ap ...

Wrapping an anonymous function in a wrapper function in Typescript can prevent the inferred typing

I am encountering an issue with typing while coding: function identity<T>(v: T): T{ return v; } function execute(fn: {(n: number):string}) {} execute((n) => { // type of n is 'number' return n.toFixed(); }) execute(identity(( ...

It appears that TypeScript is generating incorrect 'this' code without giving any warning

I seem to be facing some resistance filing a feature request related to this on GitHub issues, so I'll give it a shot here. Here is the code snippet that caused me trouble: export class Example { readonly myOtherElement: HTMLElement; public ...

Incorporating Auth0 into NestJS for Enhanced Security on gRPC Endpoints

I have been working on implementing NestJS Guards for Authentication and Authorization in my gRPC Services built with NestJS. @GrpcMethod(USER_SERVICE_NAME, 'GetUser') private getUser(req: GetUserRequest): Promise<GetUserResponse> { ret ...

Tips for soothing the TypeScript compiler

It seems like TypeScript is heavily influenced by Microsoft's interpretation of the DOM and JavaScript. But what if I'm not concerned with Internet Explorer and Edge? Unfortunately, I'm encountering issues with TypeScript... For instance, w ...

A simple method in JavaScript/TypeScript for converting abbreviations of strings into user-friendly versions for display

Let's say I am receiving data from my backend which can be one of the following: A, B, C, D Although there are actually 20 letters that could be received, and I always know it will be one of these specific letters. For example, I would like to map A ...

What is the best way to save code snippets in Strapi for easy integration with SSG NextJS?

While I realize this may not be the typical scenario, please listen to my situation: I am using Strapi and creating components and collections. One of these collections needs to include code snippets (specifically typescript) that I have stored in a GitH ...