What is the best way to distinguish between a void type and an any type?

Is there a reliable way to distinguish between the types void and any in TypeScript?

type IsAny = void extends any ? true : false   // true

type IsVoid = any extends void ? true : false  // true

It seems that based on the above code snippet, it's not straightforward to determine whether a type is void or any. Are there any alternative methods to differentiate between these two types?

Answer №1

void and any are not mutually exclusive: a void is also considered an any. This can be observed by combining them in a union type. If they were truly exclusive, void would not remain when only any is present:

type T = void | any // results in any

Due to this, it makes sense that your IsAny resolves to true.

On the other hand, for your IsVoid type, it evaluates to boolean, which essentially represents true | false. By substituting true and false with something else like 1 and 2, you will end up with 1 | 2.

This behavior stems from the fact that the any type could either be exactly void or something different than void. Therefore, we cannot definitively state if it extends void or not.

If you wish to determine whether a type is specifically any with no additional characteristics, or precisely void without any adjustments, you can utilize the following approach (derived from this provided solution):

type IsStrictAny<T> = 0 extends (1 & T) ? T : never;

type A = IsStrictAny<any> // results in any
type B = IsStrictAny<void> // leads to never

type IsVoid<T> = T extends void ? T : never
type IsNotStrictAny<T> = T extends IsStrictAny<T> ? never : T
type IsStrictVoid<T> = IsVoid<T> & IsNotStrictAny<T>

type C = IsStrictVoid<any> // results in never
type D = IsStrictVoid<void> // results in void

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

Unable to include custom matchers for Jasmine in an Angular project with Typescript

My current challenge involves adding multiple new custom matchers to jasmine and utilizing them effectively. I aim to create a file that registers 2 matchers, making all matchers readily available for each test file with just one registration. In this cas ...

In TypeScript, values other than numbers or strings can be accepted as parameters, even when the expected type is a

The issue I am encountering with TypeScript is quite perplexing, especially since I am new to this language and framework. Coming from a Java background, I have never faced such a problem before and it's presenting challenges in my bug-fixing efforts ...

Show a single image sequentially using Angular 8

I am facing an issue with displaying avatars for each object from a MongoDB database. Currently, when I display multiple objects, all the avatars are being displayed for each object instead of just one avatar per object. Here is the code snippet that I a ...

A guide on utilizing useState with Typescript to declare and update an array of strings

I am facing an issue with the code below: interface ISTx { tx: Array<string>, setTx: any } const [tx, setTx] = useState<ISTx>([]) //Argument of type 'never[]' is not assignable to parameter of type 'ISTx setTx(oldArr ...

The power of Vue reactivity in action with Typescript classes

Currently, I am working on a Vue application that is using Vue 2.6.10 along with Typescript 3.6.3. In my project, I have defined a Typescript class which contains some standard functions for the application. There is also a plugin in place that assigns an ...

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 ...

Having trouble with adding multiple items to an SP list using sp/pnp as I keep encountering an error with the "createBatch()" method

I've been referring to the documentation at to guide me, but I'm encountering an issue with the following code snippet: import { SPFI, spfi, SPFx } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists"; impo ...

What is the best way to incorporate audio playback while browsing files on an HTML5 webpage with TypeScript?

<input type="file" id="soundUrl" (change)="onAudioPlay()" /> <audio id="sound" controls></audio> This is the HTML code I'm working with, and I'm looking to trigger audio playback after a user selects an MP3 file using TypeScrip ...

Creating a function in TypeScript that returns a string containing a newline character

My goal is to create a function that outputs the text "Hello" followed by "World". However, my current implementation does not seem to be working as expected. export function HelloWorld():string{ return "Hello"+ "\n"+ "W ...

Typescript integration with Sequelize CLI for efficient database migrations

According to the Sequelize documentation, it claims to work with Typescript. However, for it to be fully functional in a production environment, DB migration scripts are necessary. The issue arises when using the Sequelize CLI as it only generates and runs ...

Implement real-time word counting in Angular as users type

I am looking to monitor word count in real-time as a user enters text into a textarea field If the word limit of 100 is exceeded, further typing should be restricted I aim to display the word count dynamically as the user types wordCounter() This functi ...

When invoking an external API within a Firebase Cloud Function, it may result in a

I've been attempting to use a basic API for currency conversion within a Firebase Cloud Function written in Typescript, but I keep getting a 'null' response. import { https } from 'firebase-functions'; import * as axios from ' ...

A guide on exposing TypeScript classes globally through a WebPack bundle in JavaScript

Currently delving into TypeScript, my aim is to gradually replace JS with TS. However, due to having numerous JS files, my strategy involves creating new classes in TS and incorporating them into my existing JS files for the time being. Eventually, I plan ...

Processing HTTP requests routed from Firebase Hosting to Cloud Functions

I'm currently working on integrating data patching with my Firestore database using http. My goal is to achieve this without relying on an external server, by utilizing Firebase Hosting and Functions. Firstly, I set up my Firebase project and importe ...

React type error: The argument 'profile' cannot be assigned to the parameter of type 'ComponentType<never>'

I've recently started learning TypeScript and I'm struggling with this particular issue. Below is the code I'm working on. import { IProps, IState } from './types'; class Profile extends Component<RouteComponentProps & I ...

What is the process for displaying all items within an object in Ionic 3?

Perhaps my question is not very clear, but what I am attempting to do is when the Feed item in the categories screen is clicked, all companies related to Feeding will be listed on the companies screen. I am quite confused because each category may have mu ...

Restricting access to tabPanel in tabView when a tab is clicked using Angular

In my tabview, I have multiple tabpanels and I am able to programmatically control it using the [activeIndex] property. However, I am facing an issue where I want to display an alert and deny access to a specific tab if a certain variable is set to false. ...

Implementing Read-Only Properties in Interfaces and/or Classes

I am currently working on a class that acts as a Model and I want to ensure that the data within it is read-only. While this may seem straightforward at first, things get more complicated when dealing with nested data structures. Let me provide an example ...

To handle async actions in Typescript with React and Redux, ensure that all actions passed to axios are plain objects. If you need to perform

Looking for assistance with Typescript, React, and Redux. export function fetchAllMeals (subject: string){ axios .get(`https://www.themealdb.com/api/json/v1/1/search.php?s=${subject}`) .then((response: any) => { console.log(response.data) ...

Steps to fix the issue of 'Property 'foo' lacks an initializer and is not definitely assigned in the constructor' while utilizing the @Input decorator

What is the proper way to initialize a property with an @Input decorator without compromising strict typing? The code snippet below is triggering a warning: @Input() bar: FormGroup = new FormGroup(); ...