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

Removing scrollbar from table in React using Material UI

I successfully created a basic table using react and material UI by following the instructions found at: https://material-ui.com/components/tables/#table. The table is functioning properly, but I am finding the scrollbar to be a bit inconvenient. https:// ...

Resolving issues with Typescript declarations for React Component

Currently utilizing React 16.4.1 and Typescript 2.9.2, I am attempting to use the reaptcha library from here. The library is imported like so: import * as Reaptcha from 'reaptcha'; Since there are no type definitions provided, building results ...

TS7030: In Angular13, ensure that all code paths within the guard and canActivate methods return a value

Having trouble using guards for an unlogged user and constantly facing errors. Error: TS7030 - Not all code paths return a value. Below is my auth.guard.ts file: import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from &a ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...

Choose the object's property name using TypeScript through an interface

Consider a simplified code snippet like the following: interface MyBase { name: string; } interface MyInterface<T extends MyBase> { base: MyBase; age: number; property: "name" // should be: "string" but only p ...

Debugger for Visual Code unable to locate URL in Microsoft Office Add-in

I recently installed the Microsoft Office Add-in Debugger VS code extension, but I'm having trouble getting it to work despite following the instructions. Every time I try, an error message pops up: Upon inspecting my launch.json file, I found this U ...

What causes a double fill when assigning to a single cell in a 2-dimensional array in Javascript?

I stumbled upon this code snippet featured in a challenging Leetcode problem: function digArtifacts(n: number, artifacts: number[][], dig: number[][]): number { const land: boolean[][] = new Array(n).fill(new Array(n).fill(false)) console.log ...

Using Angular2's NgFor Directive in Components

I am faced with the challenge of converting a tree-like structure into a list by utilizing components and subcomponents in Angular 2. var data = [ {id:"1", children: [ {id:"2", children: [ {id: "3"}, {id: "3"}, {i ...

Issues regarding ambient getters and setters

Recently, I encountered an issue with my open-source library called Firemodel. The library utilizes ES classes and getters/setters within those classes. Everything was working smoothly until my VueJS frontend code started flagging every instance of these g ...

How to Route in Angular 5 and Pass a String as a Parameter in the URL

I am currently working on an Angular project that focuses on geographic system data. The concept is as follows: I have a component with the route: {path: 'home'}. I aim to pass a geojson URL along with this route, making it look like this: {pat ...

Dynamic table row that expands to show additional rows sourced from various data sets

Is there a way to expand the table row in an angular-material table when it is clicked, showing multiple sets of rows in the same column as the table? The new rows should share the same column header but not necessarily come from the same data source. Whe ...

How can a parent's method be activated only after receiving an event emitter from the child and ensuring that the parent's ngIf condition is met?

Every time the element in the child template is clicked, it triggers the method activateService(name) and emits an event with the name of the selected service using the event emitter serviceSelected. The parent component's method scrollDown(name) is t ...

Making a quick stop in Istanbul and NYC to collect a few important files

Setting up Istanbul/Nyc/Mocha for test coverage in my project has been a bit of a challenge. While I was successful in running Nyc, I noticed that not all the .ts files in my project were being picked up for test coverage. When I execute npm run coverag ...

Customize nestjs/crud response

For this particular project, I am utilizing the Nest framework along with the nestjs/crud library. Unfortunately, I have encountered an issue where I am unable to override the createOneBase function in order to return a personalized response for a person e ...

Unable to compile TypeScript files using gulp while targeting ES5

After starting my first Angular2 app, I encountered an issue where I couldn't use gulp to compile for es5. Below is the dependencies file: "dependencies": { "@angular/common": "2.0.0", "@angular/compiler": "2.0.0", "@angular/compiler-cli ...

Developing mongoose models using TypeScript for subdocuments

Exploring the integration of mongoose models with typescript, following a guide available at: https://github.com/Appsilon/styleguide/wiki/mongoose-typescript-models. Unsure how arrays of subdocuments align with this setup. For instance, consider the model ...

Filtering relations in TypeORM can be achieved by using various query criteria

Hello, I have a couple of questions regarding TypeORM in TypeScript. Using Find() Only: I have two tables in my database - Users and Sessions. I am interested in retrieving a specific User along with all their Sessions where the sessions_deleted_at column ...

Injecting Dependencies in Angular 2 Without Using the Constructor

Exploring DI in Angular 2 has led me to implement a REST-Client using generic subtypes for concrete Datatypes like this: class RESTClient<T>{ constructor() { var inj = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]); this. ...

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...

Tips for adding a border to a table cell without disrupting the overall structure of the table

Looking for a way to dynamically apply borders to cells in my ng table without messing up the alignment. I've tried adjusting cell width, but what I really want is to keep the cells' sizes intact while adding an inner border. Here's the sim ...