Checking for undefined based on certain conditions

When looking at the following code snippet

type stringUndefined = "string" | undefined;

type What<T> = T extends undefined ? "true" : "false";

const no : What<stringUndefined> = "";

The value of 'no' ends up being

"true" | "false"
, rather than just "true" as anticipated.

You can try running this code in TS-Playground

https://i.sstatic.net/kWgQS.png

Edit:

It is important to note that strict null checks are enabled

Answer №1

"string" | undefined does not have the same extension as undefined, as it includes the possibility of being "string".

On the other hand, undefined does extend "string" | undefined because the components of a union type are considered extensions or refinements of the union itself. Therefore:

type StringLiteralOrUndefined = "string" | undefined;

type What<T> = undefined extends T ? true : false;

type X = What<StringLiteralOrUndefined>;
//   ^? type X = true

type UnrelatedType = string | number;

type Y = What<UnrelatedType>;
//   ^? type Y = false

Interactive Example

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 are the distinctions between generic and discriminated types?

Hi there, I've been thinking of an idea but I'm not sure how to implement it or if it's even possible. Is there a way to create a type SomeType where the first property can be any value from the set T, but the second property cannot be the ...

Inspect the TypeScript typings within Svelte documents directly from the terminal

When I run tsc --noemit, it successfully checks for type errors in the codebase. However, I have encountered an issue where it does not seem to check .svelte files. Is there a way to enable this functionality? I can see the type errors in .svelte files wh ...

Creating personalized mapping for TypeScript objects

I have a TypeScript object structure that resembles the following: { "obj1" : { object: type1;}; "obj2" : { object: type2;}; "obj3" : { object: type3;}; "obj4" : { object: type4;}; "obj5" ...

Authentication of users using NextJS Dashboard App API

I am currently following this tutorial, but instead of fetching data via a PostgreSQL request, I want to utilize an API. When I call an async function with await, it initially returns undefined and then the user object after receiving a response from the ...

Customizing dropzone color while dragging an image in Angular

I have been using Angular and created an image input field. Within this input field, I implemented a dropzone that allows users to drag files into it. Is there a way for me to modify the background of the dropzone when a file is being dragged into it? Thi ...

Universal function for selecting object properties

I've recently delved into TypeScript coding and have run into a puzzling issue that has me stumped. Take a look at the code snippet below: interface testInterface { a: string; b: number; c?: number; } const testObject: testInterface = { a: & ...

Exploring the incorporation of an inclusive switch statement within a Redux reducer utilizing Typescript. Strategies for managing Redux's internal @@redux actions

After conducting extensive research, I have yet to discover a definitive answer to this query. There is a question posted on Stack Overflow that provides guidance on how to implement a thorough switch statement: How can I ensure my switch block covers al ...

"Exploring the world of Typescript with the Drawflow library

Currently, I am integrating the fantastic Drawflow library created by @Jerosoler (available at: https://github.com/jerosoler/Drawflow) into my PrimeNg project. User @BobBDE has provided typescript definitions for this library here: https://www.npmjs.com/p ...

The guard check may not be enough to prevent the object from being null

Hello, I am facing an issue with the Object is possibly "null" error message in my Node.js + Express application. How can I resolve this problem? REST API export const getOrderReport = async ( req: Request<{}, {}, IAuthUser>, res: Resp ...

TypeScript and Angular: Error Encountered when Trying to Combine Two Arrays

I'm attempting to combine two arrays of the same type that are nested within a "parent" array. The end goal is to flatten the structure. Below is the code I have been using: ngOnInit() { this.Logs.getAllLogs() .subscribe(logs => { ...

Utilizing the ternary operator for variable typecasting

While trying out is_numeric($var) ? (Int)$var : (String)$var;, the idea of potentially shifting the ternary operator to where the variable is cast crossed my mind: echo (is_numeric($var) ? Int : String)$var; To no surprise, it didn't function as exp ...

Visibility of Input-properties in Angular 2

I am encountering an issue where a component parent is calling another component child with an input-property. Although the property is available in the child's template, it does not seem to be accessible within the constructor or OnInit functions. I ...

The application's functionality does not support the return type of `express-session

this.app.use( session({ // session configuration }) ); Encountering an error when passing the session configuration as shown above: Argument of type 'RequestHandler<ParamsDictionary, any, any, any>' is not assignabl ...

React Native Material - Implementing a loading indicator upon button press

With React Native Material, I am trying to implement a loading feature when a button is clicked. The goal is to show the "loading" message only when the button is active, and hide it otherwise. Additionally, I would like for the loading message to disappea ...

Tips for saving metadata about properties within a class

I am looking to add metadata to properties within classes, specifically using abbreviations for property names. By using annotations like @shortName(abbreviated), you can label each property as follows: function shortName(shortName: string){ return fu ...

Node path response not being properly configured

Just diving into the world of node and typescript and could use a bit of guidance. Currently utilizing node/express/postres as backend and leveraging https://github.com/typeorm/typeorm as an orm, which offers a function to open a connection structured as f ...

How to efficiently store and manage a many-to-many relationship in PostgreSQL with TypeORM

I have a products entity defined as follows: @Entity('products') export class productsEntity extends BaseEntity{ @PrimaryGeneratedColumn() id: number; //..columns @ManyToMany( type => Categories, categoryEntity => cat ...

When executing npm release alongside webpack, an error is triggered

Currently, I am following a tutorial provided by Microsoft. You can access it through this link: https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr-typescript-webpack?view=aspnetcore-3.1&tabs=visual-studio However, when attempting to run ...

The type 'IContact[]' given does not match the expected type 'FetchContactsSuccessPayload' for the parameter

I've been diving into my project involving react redux-saga with TypeScript and I'm facing an issue with a type error within my saga file. This is my first experience with TypeScript. The error originates from the saga.ts file, specifically this ...

The error message "xxxx" is not recognized as a valid type

When I attempted to compile the code below, I encountered an issue: #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <map> using namespace std; map<char, int> mapDial; mapDial[&a ...