Incorrectly asserting the data type of a union

I am having trouble getting the type assertion to work in this specific scenario.

Here is a Playground Link

type Letter = "A" | "B"

type Useless = {}

type Container<T> =
    Useless |
    {
        type: "container"
        value: T
    }

function transform<X extends Letter, Y extends Letter>(container: Container<X | Y>): asserts container is Container<X> {
    // custom logic
}

let container: Container<"A" | "B"> = undefined as any

// Asserts no B
transform<"A", "B">(container)

container // Container<"A" | "B">
          // Container<"A"> when Useless is commented
          // I want Container<"A">

I want container to be of type Container<"A">.

Removing type Useless altogether makes it work as expected.

Replacing type Useless with type Useless = { key: string } results in container being of type Useless instead of Container<"A">.

How can I achieve the desired type of Container<"A">?

Answer №1

It is somewhat unclear to me why TypeScript encounters issues in this scenario. My assumption is that the union with a generic, where T has no effect, can sometimes cause confusion.

When the code is separated, it seems to function correctly for me. I believe that in this context, the Useless type always asserts itself?

type Letter = "A" | "B"

type Useless = {}

type Container<T> =
    {
        type: "container"
        value: T
    }

type Input<T> = Useless | Container<T>

function transform<X extends Letter, Y extends Letter>(container: Input<X | Y>): asserts container is Container<X> {
    // custom logic
}

let container: Input<"A" | "B"> = undefined as any

// Asserts no B
transform<"A", "B">(container)

container // Container<"A" | "B">
          // Container<"A"> when Useless is commented out
          // I expect Container<"A">

Playground

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

Understanding how to infer the type of a function when it is passed as an argument

Looking at the images below, I am facing an issue with my function that accepts options in the form of an object where one of the arguments is a transform function. The problem is that while the type of the response argument is correctly inferred for the e ...

I am searching for a way to retrieve the event type of a svelte on:input event in TypeScript, but unfortunately, I am unable to locate it

In my Svelte input field, I have the following code: <input {type} {placeholder} on:input={(e) => emitChange(e)} class="pl-2 w-full h-full bg-sand border border-midnight dark:bg-midnight" /> This input triggers the fo ...

How to prevent value overwriting when adding dynamic fields in Angular 7?

In my current project using Angular, I am tasked with setting up configuration using 4 specific fields: Department Name (select option) Service Name (select option) Status (text input) Level (text input). I need to be able to add multiple sets of these ...

What is the best way to maintain the correct 'this' context for a function that is outside of the Vue

I'm struggling with my Vue component and encountering some errors. <script lang="ts"> import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, va ...

Narrowing Down State Types

I am working on a functional component in NextJS with props passed from SSR. The component has a state inside it structured like this: const MyComponent = ({err, n}: {err?: ErrorType, n?: N})=>{ const [x, setX] = useState(n || null) ... if(e ...

What exactly is a NativeScript app: is it the experience users have on their mobile devices, or the product they download from the app store?

Currently, I am diving into the world of Angular and exploring how to develop Angular applications with TypeScript while working on a C# ASP.Net Core Web Api project as the server side component. My question is this - if I create a NativeScript app in add ...

The type undefined cannot be assigned to the type even with a null check

When looking at my code, I encounter an error stating Argument of type 'Definition | undefined' is not assignable to parameter of type 'Definition'. Even though I am checking if the object value is not undefined with if (defs[type] != u ...

Using React for passing data

In the snippet found in "CameraPage.tsx", there is a logical function that is responsible for fetching camera images. This function simply makes a GET request to search for images stored in the backend, which will later be displayed on the FrontEnd. The op ...

Update the nest-cli.json configuration to ensure that non-TypeScript files are included in the dist directory

I've been searching for a solution for hours now: I'm developing an email service using nestJS and nest mailer. Everything was working fine until I tried to include a template in my emails. These templates are hbs files located in src/mail/templ ...

Utilizing the Filter Function to Eliminate an Element from an Array

I am a beginner in the world of React and I'm currently working on developing a simple timesheet tool where users can add tasks and save them. My tech stack includes React and Typescript. Currently, my main component has an empty array for tasks and ...

Tips for simulating the getCustomRepository function in typeORM

I am facing a challenge in unit-testing a class that has a getCustomRepository method in its constructor. I'm struggling to find an easy way to mock it. Below is the code for my class: import {getCustomRepository} from 'typeorm'; export cl ...

Tips for excluding test files in next.js when building

I am currently developing a next.js application with tests integrated within the page directory structure. In order to achieve this, I have made necessary configurations in the next.config.js file. const { i18n } = require('./next-i18next.config' ...

Unable to translate text on the loading page

Encountering a peculiar issue with the translate service. Here's how I set it up: export class AppComponent implements OnInit { constructor( private translateService: TranslateService, angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics ...

React: Content has not been refreshed

MarketEvent.tsx module is a centralized controller: import * as React from 'react'; import EventList from './EventList'; import FullReduce from './FullReduce'; import './MarketEvent.less' export default class Mark ...

hiding html elements by using the display property set to none instead of physically removing

I am currently utilizing an if-else statement to display different HTML structures. As a result, the entire HTML is being rendered twice. Is there a way we can utilize 'display: none' instead? I attempted to use it in th ...

Scoped variable in Typescript producing a generated Javascript file

I'm currently learning TypeScript through an online course, and I've encountered a problem that seems to be related to a VSCode setting. Whenever I compile app.ts, it generates the app.js file, but I immediately encounter a TypeScript error. It& ...

Get React-table TS up and running on your local machine using VS Code

Objective: I am trying to get React-table working with TypeScript on my local computer. Challenge: The code is based on this page https://codesandbox.io/s/gkzg3?file=/src/makeData.ts However, when I attempt to apply the code on my local computer, I ...

Isolating a service from a component based on conditions in Angular 5

Within my root module, I have a service that is shared among all components. One of these components is named ComponentX module providers: [ BiesbroeckHttpService ], component constructor(private biesbroeckHttpService: BiesbroeckHttpService){} Som ...

Error: Unhandled promise rejection: Trying to access a property of null (specifically 'branch') causing a TypeError

While developing a dashboard for an Angular application, I encountered an error when trying to access the dashboard: ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of null (reading 'branch') TypeError: Cannot read propert ...

The issue of returning a boolean value in an rxjs function leading to failure

Hey there, I am currently learning about rxjs and I want to create an observable that returns either true or false. This is my attempted code: checkLoggedIn(): Observable<boolean> { // Check with the server if the user is logged in if(this._tok ...