Definition of assignability for intersection types

Exploring the concept of intersection types, we can find a definition in

https://github.com/microsoft/TypeScript/pull/3622

When A & B is assignable to X, it means that either A is assignable to X or B is assignable to X.

type A = {x:1}
type B = {y:1}

type I = A & B 

declare function f(t:{x:1;y:1}):void

let i:I = {} as I
let a:A = {} as A
let b:B = {} as B

f(a) // error
f(b) // error
f(i) // ok

By looking at A {x:1} and B {y:1}, we see that they are not directly assignable to X {x:1;y:1}. However, when combining them into I, it becomes assignable to X.

Is this definition incorrect? Or am I missing something?

Answer №1

The explanation seems adequate.


Another method to express "X is a subtype of Y" is by stating that "X is assignable to Y". Therefore, you could reword the definition as follows:

If A is a subtype of X or B is a subtype of X, then A & B is a subtype of X.

For instance, if you have a value of type Cat & Warm, it can be stored in a variable of type Cat, Warm, and even Animal due to the fact that Cat is a subtype of Animal. In essence, Cat & Warm is a subtype of Cat, Warm, and Animal.


In the given scenario, A {x:1} and B {y:1} are not assignable to X {x:1;y:1}, but I is assignable to X.

Indeed, A cannot be assigned to A & B, and similarly, B cannot be assigned to A & B. The clarification implies that A & B can be assigned to A and also to B.

When stated that "X is assignable to Y", it signifies that having a variable x of type X is permissible:

const y: Y = x

Hence, the following code segments are acceptable:

const a: A = a_and_b
const b: B = a_and_b

However, these expressions are invalid:

const ab: A & B = a
const ab: A & B = b

Example (playground link):

type A = {x: 1} | {z: 42}
type B = {x: 1}
type C = {y: 2}

function f(bc: B & C) {
    const b: B = bc  // Acceptable because B & C can be assigned to B
    const c: C = bc  // Acceptable because B & C can be assigned to C
    const a: A = bc  // Valid since B is assignable to A, thus B & C is assignable to A
}

function g(b: B) {
    const bc: B & C = b  // Not valid, does not work the other way around
}

In your specific case, when invoking the functions f with a and b, you're essentially replicating what's happening in the function g. This will generate an error because A cannot be assigned to A & B, and likewise, B cannot be assigned to A & B.

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

Angular error: The function redirectToLogin in src_app_app_routing_module__WEBPACK_IMPORTED_MODULE_0__.AppRoutingModule is not defined

I'm attempting to redirect users from the homepage to the login page using home.component.ts. Within this file, I've invoked a static method called "AppRoutingModule.redirectToLogin()" that I've defined in app-routing.module.ts by importing ...

The resolver function in the Nextjs higher order API is not defined

I am trying to create a custom wrapper function for my NextJs API routes that will verify a JWT in the request, validate it, and then execute the original API handler. Here is how I have defined my wrapper function: interface ApiError { message: string, ...

Guide to making a Material Design Radial effect animation

I am looking to create a unique toolbar effect by following the material design radial reaction choreography guideline. https://i.stack.imgur.com/6oB8r.gif I want to achieve this using an angular 2 transition, but I need some guidance on how to implement ...

How to correctly deserialize dates in Angular 5

When working with Angular 5, I have encountered an issue where JSON data from an API is not properly deserialized into dates within an array. My model includes a definition like this: export interface ProcessDefinition { _id?: string; proces ...

Encountering an error while trying to import JSON in TypeScript

I am in need of using mock JSON data to test the rendering of my front-end. import MOCK_FAQ from '../../mocks/FAQ.json'; However, when attempting to import the file, I encountered this exception: Cannot find module '../../mocks/FAQ.json&a ...

What could be the reason for the Angular2 Component property not appearing on my webpage?

Here is the code snippet I am working with: import {Component} from "@angular/core"; @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> <h2>{{secondTitle}}</h2> <main-page></ma ...

Is there a way to reset useQuery cache from a different component?

I am facing an issue with my parent component attempting to invalidate the query cache of a child component: const Child = () => { const { data } = useQuery('queryKey', () => fetch('something')) return <Text>{data}& ...

Compilation error occurred when running Angular with mat-form: ngcc encountered an issue while processing [email protected]

Currently dealing with a compile error in a small mat-form example that I created. Unfortunately, I am unable to pinpoint the exact issue causing this error. If you have a moment, please take a look at the code here: https://stackblitz.com/edit/angular-iv ...

Encountering issues with managing CometD channels within Angular 2

After dabbling in Angular2 and Typescript, I decided to challenge myself by creating an application using plain javascript with the CometD library. The goal of this app was to retrieve data from a CometD channel and present it to the user in some way. So, ...

Angular2 - receiving an error message stating that this.router.navigate does not exist as a

Currently, I am delving into the world of Angular2 with Ionic and working on crafting a login page. However, upon loading the page, an error surfaces: 'router.initialNavigation is not a function' To address this issue, I inserted '{initialN ...

Applying a setvalidator to a FormControl doesn't automatically mark the form as invalid

HTML code <div> <label for="" >No additional information flag:</label> <rca-checkbox formControlName="noAdditionalInfoCheckbox" (checkboxChecked)="onCheckboxChecked($event)"></rca-chec ...

Is it possible to create a .d.ts file to easily share constants between JavaScript and TypeScript?

Currently, I am in the midst of a node.js project that involves both TypeScript and JavaScript due to historical reasons. My goal is to establish project-wide constants that can be utilized in both languages. Initially, I thought about creating a .js file ...

Acquiring an element through ViewChild() within Angular

I am in need of a table element that is located within a modal. Below is the HTML code for the modal and my attempt to access the data table, which is utilizing primeng. <ng-template #industryModal> <div class="modal-body"> <h4>{{&a ...

Resolving Angular Issue: Error code (5, 12) TS2314 - Solving the requirement for 1 type argument in the 'Array<T>' generic type

Encountered an issue in the JSON data within my typescript file. I'm working on creating an Angular API that performs a git-search operation. Initially, I had the JSON data set up correctly but then I modified all data values to their respective data ...

Create and export a global function in your webpack configuration file (webpack.config.js) that can be accessed and utilized

Looking to dive into webpack for the first time. I am interested in exporting a global function, akin to how variables are exported using webpack.EnvironmentPlugin, in order to utilize it in typescript. Experimented with the code snippet below just to und ...

Angular2 - Breaking down applications into reusable components

Utilizing custom properties permits seamless data binding between multiple components. <section id="main"> <app-home [dict]="dict">Hello there!</app-home> </section> In this scenario, dict serves ...

Leveraging Generic Types in React with TypeScript for Dynamically Assigning HTML Props based on Element Tags

I am frequently in need of a component that is essentially just a styled HTML tag. A good example is when I want to create beautifully styled div elements: // Definitions const styledDiv = (className: string) => { const StyledDiv = React.FC<HTMLA ...

Executing a function on a converted TypeScript object

My experience with using Cloud Firestore has been smooth in casting to an object, but I have encountered an issue when trying to call methods on that object. Below is the model definition I am working with - contact.ts export class Contact { id: string ...

The value of req.headers('Authorization') has not been defined

I'm experiencing difficulty with my code as the token is coming back as undefined. Here is the frontend section: export const fetchUser = async (token: any) => { const res = await axios.post('/user/getuser', { headers ...

What steps are needed to develop a TypeScript component within Angular framework?

I've been attempting to develop an Angular Component in TypeScript. I'm trying to utilize document.createElement to build a toolbar within my component, but it's not appearing. Below is my Component code: import {Directive, Component, boot ...