Compiling Typescript with union types containing singleton types results in errors

I'm having trouble understanding why the code below won't compile:

type X = {
  id: "primary"
  inverted?: boolean
} | {
  id: "secondary"
  inverted?: boolean
} | {
  id: "tertiary"
  inverted?: false
}


const a = true
const x: X = {
  id: a ? "primary" : "secondary"
}

x should be valid for any scenario.

But there's an error in compilation:

test.ts:14:7 - error TS2322: Type '{ id: "primary" | "secondary"; }' is not assignable to type 'X'.
  Type '{ id: "primary" | "secondary"; }' is not assignable to type '{ id: "tertiary"; inverted?: false; }'.
    Types of property 'id' are incompatible.
      Type '"primary" | "secondary"' is not assignable to type '"tertiary"'.
        Type '"primary"' is not assignable to type '"tertiary"'.

Answer №1

When dealing with type checking, a peculiar behavior arises. If we use the ternary expression a ? "primary" : "secondary", the resulting type will be "primary" | "secondary". As a result, the object literal is typed as { id : "primary" | "secondary" }.

The way unions are evaluated dictates that for an object literal to be considered compatible with the union, it must be compatible with at least one member of the union. However, in the case above, the object literal type does not align with either union member, leading to an error.

To resolve this issue, the simplest solution is to perform the check outside:

const x3: X = a ? { id: "primary" } : { id: "secondary" }

Alternatively, a type assertion can also be used.

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 is the best approach for testing the TypeScript code below?

Testing the following code has been requested, although I am not familiar with it. import AWS from 'aws-sdk'; import db from './db'; async function uploadUserInfo(userID: number) { const user = db.findByPk(userID); if(!user) throw ...

Angular - Implementing validation for maximum character length in ngx-intl-tel-input

Utilizing the ngx-intl-tel-input package in my Angular-12 project multistep has been quite promising. Below is a snippet of the code: Component: import { SearchCountryField, CountryISO, PhoneNumberFormat } from 'ngx-intl-tel-input'; expor ...

How to utilize the async pipe on an observable<Object> and connect it to a local variable in the HTML using Angular

Hey there! So, I have this observable called user$ which has a bunch of properties such as name, title, and address. component{ user$:Observable<User>; constructor(private userService:UserService){ this.user$ = this.userService.someMethodRet ...

Determine the amount of time that can be allocated based on the attributes contained within the object

I am faced with a JSON structure like the one below: var meetings = [ { id: '1', start_time: "2020-11-15T08:30:00+00:00", end_time: "2020-11-15T14:15:00+00:00" }, { id: '2', start_time: &quo ...

Changing the appearance of a specific child component in React by referencing its id

There is an interface in my code. export interface DefaultFormList { defaultFormItems?: DefaultFormItems[]; } and export interface DefaultFormItems { id: string; name: string; formXml: string, isDefaultFormEnable: boolean; } I am looking ...

Issues arise in Angular 4 when the "Subscribe" function is repeatedly invoked within a for/switch loop

My array of strings always changes, for example: ["consumables", "spells", "spells", "consumables", "spells", "consumables", "spells", "characters", "characters", "consumables"] I iterate through this array and based on the index, I execute different .su ...

Encountered an error while trying to retrieve data from

Having trouble with file uploads to the S3 bucket using @aws-sdk/client-s3 library and encountering errors when uploading files larger than 70kbps: `TypeError: Failed to fetch at FetchHttpHandler.handle (fetch-http-handler.js:56:13) at PutObjectCommand ...

Having trouble importing Sequelize in Angular?

I'm encountering an issue in my app where I am unable to import the sequelize package. The error message reads: chunk {main} main.js, main.js.map (main) 2.02 kB [initial] [rendered] chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 691 b ...

Creating a sophisticated union type by deriving it from another intricate union type

I have a unique data structure that includes different types and subtypes: type TypeOne = { type: 'type-one', uniqueKey1111: 1, }; type TypeTwo = { type: 'type-two', uniqueKey2222: 2, } type FirstType = { type: 'first&apo ...

Issue with ngFor displaying only the second item in the array

There are supposed to be two editable input fields for each section, with corresponding data. However, only the second JSON from the sample is being displayed in both sections. The JSON in the TypeScript file appears as follows: this.sample = [ { "se ...

When upgrading from ng15 to ng16, beware of the error message stating that the type '(event: RouterEvent) => void' cannot be assigned to type '(value: Event_2) => void.'

section, I encountered issues with my Angular project after upgrading from ng15 to ng16. Specifically, errors are arising when trying to implement the code snippet below. Can anyone provide insights on what may be causing problems with the event argument ...

Using TypeScript generics to add constraints to function parameters within an object

My Goal: Imagine a configuration with types structured like this: type ExmapleConfig = { A: { Component: (props: { type: "a"; a: number; b: number }) => null }; B: { Component: (props: { type: "b"; a: string; c: number }) =& ...

Interpolation is not available for my Angular application

I am having trouble with using interpolation on my input in this code. I tried setting the value of the input to be the same as the User's username, but it doesn't seem to work. <ion-header> <ion-toolbar> <ion-buttons slot=&q ...

`How to Merge Angular Route Parameters?`

In the Angular Material Docs application, path parameters are combined in the following manner: // Combine params from all of the path into a single object. this.params = combineLatest( this._route.pathFromRoot.map(route => route.params) ...

### Setting Default String Values for Columns in TypeORM MigrationsDo you want to know how to

I'm working on setting the default value of a column to 'Canada/Eastern' and making it not nullable. This is the current setup for the column: queryRunner.addColumn('users', new TableColumn({ name: 'timezone_name', ...

Example showcasing the functionality of the react-custom-scrollbars package in a TypeScript React application

In my TypeScript React project, I am struggling to set up the react-custom-scrollbars package successfully. Despite consulting the examples provided in the GitHub repository, I have not been able to get it working. Can someone share a functional example ...

Utilizing a function within the catchError method

A function has been defined to handle errors by opening a MatSnackBar to display the error message whenever a get request encounters an error. handleError(err: HttpErrorResponse) { this.snackBar.open(err.message) return throwError(err) } When subs ...

Error caused by properties of a variable derived from an interface in the compiler

I'm confused as to why the compiler is saying that the properties "name" and "surname" don't exist on type "ITest1" within function test1. It's a bit unclear to me: interface ITest1{ name: string; surname: string; age: number; } ...

Add a hyperlink within a button element

I am looking to add a route to my reusable 'button' component in order to navigate to another page. I attempted using the <Link> </Link> tags, but it affected my CSS and caused the 'button' to appear small. The link works if ...

Converting a JSON array stored in a local file to a TypeScript array within an Angular 5 project

I'm currently working on developing a web app using Angular 5. My JSON file has the following structure: [ { "id": 0, "title": "Some title" }, { "id": 1, "title": "Some title" }, ... ] The JSON file is store ...