What is the result of using `X ? A : B` in typescript?

type TestAny = any extends 'a' ? 1 : 2 // => 1 | 2  why??? how to interpret?
type TestUnknown = unknown extends 'a' ? 1 : 2 // => 2
type TestStringA = 'a' extends 'a' ? 1 : 2 // => 1

type SomeUnion = 'a' | 'b'
type UnionDistribute<T> = T extends 'a' ? 1 : 2
type t0 = UnionDistribute<SomeUnion>  // => 1 | 2  // similar to a union

Why any extends 'a' ? 1: 2 results in 1 | 2, acting as a union. I attempted to search online for an explanation without success.

playground

Answer №1

To find a thorough explanation to this question, check out microsoft/TypeScript#40049, although it may not fully clarify the underlying reason in my opinion.

Especially take note of this comment:

@jack-williams commented on Aug 14, 2020:

It's not very well-documented outside of the source code, but in the checker, you'll discover at the relevant location:

// Return union of trueType and falseType for 'any' since it matches anything
if (checkType.flags & TypeFlags.Any) {

Thus, any is considered as a wildcard that can match both branches.

You can currently locate the code on line 15239here (GitHub doesn't allow linking to specific lines in large files like this one), and it was added in this commit within microsoft/TypeScript#21316, the pull request that introduced conditional types. Therefore, this behavior has been consistent since conditional types were implemented.

This essentially explains "why" this occurs. The official reasoning being, "since it matches anything".

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

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

Angular not successfully passing ID in for loop

I am trying to pass the res[i].id value to my ArrayList while maintaining the sequence. Can anyone help me understand why 809 and 806 are not getting added to the arrayList correctly? 0: {id: 0, ArrayListID: 809, VarName: "TEST001A"} 1: {id: 0, ...

Utilize SWR in NextJS to efficiently manage API redirection duplication

When using SWR to fetch data, I encountered an error where the default path of nextjs was repeated: http://localhost:3000/127.0.0.1:8000/api/posts/get-five-post-popular?skip=0&limit=5 Here is my tsx code: 'use client' import useSWR from &quo ...

Assign a value using the select component from Material UI

I just finished creating a dropdown menu const [selectedValue, setSelectedValue] = useState(''); const handleSelectionChange = (e: any) => { //setSelectedValue(e) console.log('value', selectedValue) } .... <Fo ...

Is it feasible to access and modify local files within an Angular project using TypeScript code in the angular component.ts file? If so, how can this be achieved?

My Angular application is built on version 4 or higher. I have a setup in my project where there is a folder containing a txt file and another folder next to it with an angular component.ts file: FolderWithFile -----file.txt ComponentFolder -----person.co ...

Error TS2322: Cannot assign type 'Promise<Hero | undefined>' to type 'Promise<Hero>'

I am currently studying angular4 using the angular tutorial. Here is a function to retrieve a hero from a service: @Injectable() export class HeroService { getHeroes(): Promise<Hero[]> { return new Promise(resolve => { // ...

Why do I keep encountering the error "global is not defined" when using Angular with amazon-cognito-identity-js?

To start, run these commands in the command line: ng new sandbox cd .\sandbox\ ng serve Now, navigate to http://localhost:4200/. The application should be up and running. npm install --save amazon-cognito-identity-js In the file \src&bso ...

Playwright script encounters module not found error

I am currently facing an issue with implementing Playwright in my project. It seems that Playwright is struggling to a) resolve path aliases and b) it is unable to locate certain npm packages that have been installed. Here is the structure of my project: ...

Issue found in VS2015 with the sequence of AngularJS TypeScript ts files within the appBundle.js file

I've been diving into AngularJS and TypeScript with the VS2015 RC Cordova TypeScript project. Recently, I created a "MyController.ts" file in the same folder as "index.ts". The code worked perfectly fine: module MyTestApp{ export class MyContro ...

Switch from Gulp-TSLint to Gulp-ESLint for enhanced code analysis!

I am currently in the process of updating a Gulp task that uses gulp-tslint to now use gulp-eslint. The code snippet below outlines the changes I need to make: const { src } = require('gulp'); const config = require('./config'); const ...

What is the best way to insert information into my SQLite database?

Hey there! I'm new to programming and recently started working on an IONIC App. However, I've hit a roadblock. My goal is to create a phone book feature where users can get random JSON contacts and save them to their sqlite database. Here's ...

Unable to simulate the navigator.language

I'm currently in the process of writing unit tests for some of my shared utility functions. As someone who is relatively new to unit testing, I am encountering difficulties when trying to mock certain global objects. Specifically, I am struggling to f ...

Using Stack and Drawer Navigations Together in React Native Navigation(v6)

I am looking to merge Stack and Drawer navigations. I have multiple screens and wish to display select screen labels in the drawer tab. <RootNavigatorStack.Navigator> <RootNavigatorStack.Screen name="DrawerTab" component={DrawerNavig ...

Can you change the method definition of a built-in class using TypeScript?

Working with the Web Audio Api in TypeScript has presented me with a minor issue. I am trying to enhance AudioParam's prototype by adding some convenience methods that can be used on any parameter. However, I keep getting an error from the compiler st ...

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

Limiting the character input in ion-textarea within Ionic 2: A step-by-step guide

In my Ionic 2 application, I need to limit user comments to less than 500 characters in a text area. What is the best way to implement this restriction? ...

Utilizing Class Types in Generics with TypeScript

Struggling to implement a factory method based on the example from the documentation on Using Class Types in Generics, but hitting roadblocks. Here's a simplified version of what I'm attempting: class Animal { legCount = 4; constructor( ...

Error: Typescript foreach loop encountering 'Expression yields void type'

Currently, I am working on setting up a cron job to monitor the completion of my tournaments and trigger some specific code upon completion. For reference, I came across this example: During deployment of my code, an error popped up as follows: ERROR: fu ...

Issue: Custom Object is returning an error stating that the property 'forEach' does not exist on type 'void'.ts(2339)

Within my code, I am dealing with a variable that can be either of type User or void. The dilemma arises when the code runs into an error message saying: Property 'forEach' does not exist on type 'void'.ts(2339). Despite trying various ...

The TypeScript compilation is not able to find index.ts at the moment

When I tried to run 'ng serve', I encountered the following error message: The TypeScript compilation is missing node_modules/angular2-indexeddb/index.ts. It is crucial to ensure that this file is included in your tsconfig under the 'file ...