Prohibit using any as an argument in a function if a generic type is

I have attempted to implement this particular solution to prevent the calling of a generic function with the second type being equal to any.

The following code snippet works fine as long as the first generic parameter is explicitly specified:

 declare function f<V = any, A extends ISmth = ISmth>(a: IfAny<A, never, A>): V;

If I need V to be the first parameter and optional (as it's the return type and cannot be inferred - either needs to be explicitly specified or simply be any), how can I correct the code?

I tried changing the default value, but it breaks any calls with an explicit first type:

declare function g<V = any, A extends ISmth = any>(a: IfAny<A, never, A>): V;

Full code here.

interface ISmth { x: number; }

type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N;

declare function f<V = any, A extends ISmth = ISmth>(a: IfAny<A, never, A>): V;
declare function g<V = any, A extends ISmth = any>(a: IfAny<A, never, A>): V;

declare var x: ISmth, y: any;

f(x); // Fine
f(y); // Fine: Argument of type 'any' is not assignable to parameter of type 'never'.

f<string>(x); // Fine
f<string>(y); // BAD: Should be an error, but compiles

g(x); // Fine
g(y); // Fine: Argument of type 'any' is not assignable to parameter of type 'never'.

g<string>(x); // BAD: Should NOT be an error
g<string>(y); // Fine: Argument of type 'any' is not assignable to parameter of type 'never'.

Answer №1

Currently, TypeScript does not support partial type argument inference, which means that this solution may not be suitable for your needs. One workaround is to create a curried function where you manually specify one type parameter and return a function with an inferred type parameter:

declare const fCurry: <V = any>() => 
  <A extends ISmth = ISmth>(a: IfAny<A, never, A>) => V;
fCurry()(x); // no error
fCurry()(y); // error
fCurry<string>()(x); // no error
fCurry<string>()(y); // error

Another approach is to create a function that accepts a dummy argument for the type parameter you want to specify manually. This argument can be null at runtime, but you can use a type assertion to inform the compiler about the intended type:

declare function fDummy<V = any, A extends ISmth = ISmth>(
  a: IfAny<A, never, A>, 
  dummy?: V
): V;
fDummy(x); // no error
fDummy(y); // error
fDummy(x, null! as string); // no error
fDummy(y, null! as string); // error

While these methods may not be perfect, they can achieve the desired behavior. Best of luck!

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

Error: Reference to an undeclared variable cannot be accessed. TypeScript, Cordova, iOS platforms

Can anyone offer some advice on what might be the issue? I'm encountering an error while building my Ionic app on the IOS platform, but everything is running smoothly on Android. ReferenceError: Cannot access uninitialized variable. service.ts:31 O ...

Setting the [required] attribute dynamically on mat-select in Angular 6

I'm working on an Angular v6 app where I need to display a drop-down and make it required based on a boolean value that is set by a checkbox. Here's a snippet of the template code (initially, includeModelVersion is set to false): <mat-checkbo ...

Updating state in React without providing a key prop is a common issue, especially when

Currently, I am working on implementing a Radio Group where I want the radio button's checked value to update when another button is clicked. In the example provided below, it seems that the desired effect can only be achieved using the "key" prop. Is ...

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...

Is it possible to modify the parameters of a function by utilizing a MethodDecorator without affecting the "this" value?

Consider a scenario where you need to dynamically modify method arguments using a decorator at runtime. To illustrate this concept, let's simplify it with an example: setting all arguments to "Hello World": export const SillyArguments = (): MethodDec ...

Troubleshooting the Hide/Show feature in React Native

As a newcomer to React Native development, I am attempting something simple. Within a React Class extending Component, I have 4 components <TouchableOpacity>. In the render function, my goal is to hide three of these components while pressing on one ...

Typescript - Keeping a log of object keys along with their corresponding key type values

Imagine having the following scenario where you need to create an object with keys that are transformed versions of the original type's values: export type CCDTypes = { AuthorisationCaseEvent: AuthorisationCaseEvent, AuthorisationCaseField: Author ...

Developing a Typescript module, the dependent module is searching for an import within the local directory but encounters an issue - the module cannot be found and

After creating and publishing a Typescript package, I encountered an issue where the dependent module was not being imported from the expected location. Instead of searching in node_modules, it was looking in the current folder and failing to locate the mo ...

Fill a dynamic form with a date sourced from the ngrx storage

How can I populate a form with data from the store if setValue and patchValue methods are not working? export class MyComponent implements OnInit, OnDestroy { public newsletterToEdit$: Observable<NewNewsletter> = this.store.selectNewsletterToEdi ...

Mastering ngClass for validation in Angular 2: Step-by-step guide

I am facing an issue with a form I have created where I applied ngclass to display an error when the form value is missing. However, the error is showing up when the form is initially loaded. It seems that by default, my input tag is invalid when the form ...

What is the reason behind permitting void functions in the left part of an assignment in Typescript?

Take a look at this Typescript snippet: let action = function (): void { //perform actions }; let result = action(); What makes it suitable for the TypeScript compiler? ...

Uploading Files with Typescript Promises

Hello everyone, I'm facing an issue where a dialog window is opening before all the files are uploaded to the server. Can anyone please guide me on what might be going wrong in my code? public UploadAll() { this.doAsyncTask().then(() => ...

The TypeScript alternative to Axios request with native fetch functionality

I have a function that sends a JWT validation request: const sendValidateJWTRequestFetch = (url: string, token: string) => fetch(url, { method: 'GET', mode: 'cors', headers: { Authorization: token, 'Ac ...

If you want to use the decorators plugin, make sure to include the 'decoratorsBeforeExport' option in your

Currently, I am utilizing Next.js along with TypeScript and attempting to integrate TypeORM into my project, like demonstrated below: @Entity() export class UserModel extends BaseEntity { @PrimaryGeneratedColumn('uuid') id: number } Unfortun ...

Display HTML tags on an HTML page using TypeScript

In my angular application, I encountered an issue where I needed to call one component inside another component. Initially, I was able to achieve this by simply using the second component's selector in the HTML of the first component: html: <div&g ...

What are the steps for changing this JavaScript file into TypeScript?

I'm currently in the process of converting this JavaScript file to TypeScript. However, I've encountered an error with the onClick function as shown below: import React from 'react'; import { Popover } from 'antd'; import A fr ...

Is there a way to create identical copies of data with the identical names?

Here is the code I have written: this.temp1.push(this.json); for(let i=0; i<this.temp1.length; i++){ if(this.temp1[i].name == this.json.name){ this.orderList[i] = this.json; this.DBorder[i] = this.order_json; } ...

Utilize CountUp.js to generate a dynamic timer for tracking days and hours

I am looking to create a unique counter similar to the one featured on this website https://inorganik.github.io/countUp.js/ that counts up to a specific number representing hours. My goal is to display it in a format such as 3d13h, indicating days and hour ...

What is the proper way to utilize bootstrap dropdown menus?

I need to create a dropdown menu similar to the one shown in this image: I attempted to use code from the following URL: https://getbootstrap.com/docs/4.0/components/dropdowns/, but unfortunately, it did not work as expected even though I have installed B ...

Using the TranslateService in Angular to externalize an array of strings

I am new to externalizing code. As I was working on developing a month picker in Angular, I initially had an array of months with hardcoded names in my typescript file: arr = ['Jan', 'Feb', 'Mar', 'Apr', 'May&a ...