Understanding how types intersect in TypeScript

I'm currently diving into Type Relations in TypeScript. Can someone help explain what happens when we intersect the types represented by these two expressions:

{a:number}[] & {b:string}[]

Does this result in

{a:number, b:string}[]

? Any clarification is appreciated.

Answer №1

Indeed, the documentation does not provide a clear explanation of operator precedence in the type definition. However, one can easily test it:

type Z = { a: number }[] & { b: string }[];

let a: Z = [];
a = [{ a: 1, b: "q" }]; // This assignment is invalid because `b` does not exist in `{ a: number }`.
a = [{ a: 1 }]; // This assignment is also invalid because `a` does not exist in `{ b: string }`.
a = [{ b: "foo" }]; // Another invalid assignment due to `b` not existing in `{ a: number }`.
a = []; // This assignment is valid.

let x: { a: number, b: string }[] = a; // This assignment is also invalid.

The results show that the assumption it resolves to { a:number,b:string } is incorrect. Initially, I assumed it would resolve to

({ a: number } | { b: string })[]
, but that's inaccurate too.

The intersection denotes "an array of elements where each element satisfies the type { a: number } and simultaneously satisfies the type { b: string }. Since a is absent in the second type and b is missing in the first, no element can fulfill the intersection. Therefore, only empty arrays can be assigned to variables typed with the intersection.

To achieve the expected outcome, a different intersection is required:

type Z2 = { a: number, b?: string }[] & { a?: number, b: string }[];

let a2: Z2 = [];
a2 = [{ a: 1, b: "q" }];

This will work as anticipated because the first type in the intersection allows elements that may optionally have b, while the second type allows elements that may optionally have a.

Answer №2

declare type T1={a:number}[];
declare type T2={b:string}[];
declare type common =T1&T2;
let x:common;
let y=[{a:1,b:'2'}];
x=y;

therefore, your answer is accurate!

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

Incorporate v-if to target a particular item within a v-for loop

On my Vue page, I have the following HTML code snippet: <div v-for="profile in lab.profiles" v-if="edit || profile.active" class="lab-tests-row-div" @mouseover=""> <div class="clickBox" :class="['clickBox-' + lab.id + ' ...

Developing play and pause capabilities using JavaScript for the existing audio player

Currently, I am developing a Chrome extension that includes an HTML popup with buttons to play audio files. However, I feel that my current approach is not the most efficient and I am struggling to find ways to simplify the process. The method I am using n ...

Experimenting with a module reliant on two distinct services

I am facing an issue with a component that relies on a service to fetch data. The service also retrieves configurations from a static variable in the Configuration Service, but during Karma tests, the const variable is showing up as undefined. Although I ...

Special react-hook designed for dynamically assigning CSS classes

I'm currently exploring React's hooks and playing around with reusing the ability to add a shadow to an element (utilizing bootstrap as the css-framework). Here is the current structure of my App: export const App: React.FunctionComponent<IA ...

Display a text over a full-screen HTML5 video

Is there a way to display text on a fullscreen video in HTML? I have tried using absolute positioning for the text and relative/fixed/none positioning for the video, but it does not work when the video is in fullscreen mode. I also attempted to call the ...

Passing events from a parent component to dynamically created child components in Angular

UPDATE: I've decided to tackle this issue in a different way by retrieving dynamic child component values in the parent component's save() function, following the accepted answer. I am attempting to create a system where a parent component emits ...

I keep encountering the following error message: " ERROR Error Code: 200 Message: Http failure during parsing for http://localhost:3000/login"

My Angular Login component is responsible for passing form data to the OnSubmit method. The goal is to send form data from the front-end application and authenticate users based on matching usernames and passwords in a MySQL database. ***This login form i ...

A guide on removing an element from a state array in a React functional component for a To-Do List application

I need help making a to-do list item disappear when clicked. The deleteHandler method is not working as expected. Can anyone provide logic on how to filter out the clicked item? import React, { useState } from 'react'; const ToDoList = () => ...

Problems with the firing of the 'deviceready' event listener in the PhoneGap application

Utilizing vs2012, I have been working on a PhoneGap application. Within this application, the following JavaScript code is being used: document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // alert("hh") ...

When using JSON.stringify on a map object, it returns an empty result

var map1= new Map(); map1.set("one",1); var map2 = new Map(); map2.set("two",2); concatMap = {}; concatMap['one']= map1; concatMap['two']= map2; JSON.stringify(concatMap); //outputs : "{"one":{},"two":{}}" I als ...

Unable to access the URL slug within the client component in Next.js version 13

In my upcoming project with Next 13, I have a client-side component that is being rendered under the route /journal/[date] Unfortunately, I'm facing an issue trying to extract the date from the URL. I attempted to use: import { useRouter } from &apos ...

Why is my Angular 2 app (TypeScript) not functioning properly?

My current project includes a component called EventListComponent import { Component } from 'angular2/core'; @Component ({ selector: 'el-events', templateUrl: 'app/events/event-list.component.html' }) export class E ...

The NextJS API is now pointing to the index.js file rather than the [id].js file

I am currently setting up an API in NextJS. In my /classes folder, I have index.js and [id].js files. The purpose of /classes/ is to retrieve all classes from the database or add a new class. The purpose of /classes/[id] is to fetch a specific class, upda ...

Assigning event to the body element

Is there a way to bind an event to the entire page, specifically the html or body tag? I am trying to achieve the following: document.addEventListener('mousemove', function() { alert('a'); }); I want an alert to be triggered whenever ...

Having trouble with NPM install because of a node-gyp issue?

We're facing issues with running "npm install" on our project. The error message states that a specific file cannot be located: fatal error C1083: Cannot open include file: 'windows.h' This error seems to be originating from the node-gyp mo ...

"What is the best way to change the props of a React component that has already been rendered from App.js

My React component, MoviesGallery.js, is set up with the following structure: class MoviesGallery extends Component { constructor(props) { super(props) this.state = { currentImage: 0 }; this.closeLightbox = this.closeLightbox. ...

Unusual naming problem encountered in DataTables when employing diverse functions

I'm encountering an unusual issue with DataTables. In the documentation, there is inconsistency in using either a capital D or lowercase d when referring to the class name: var table = $('#example').DataTable(); Sometimes it's like th ...

Using Regex to detect recurrent (similar) patterns in jQuery <input> tags

I need assistance with ensuring that users input article numbers in the correct format, like this: ABC_ABC123; AB__B2A4; ABF_323WET; ... Currently, I have a regex pattern that works for one article number: var mask1 = /^([A-Z]{2})([A-Z|_]{1})_([A-Z0-9]{ ...

Encountering a problem with the getJSON() function within the app.js file connected to a solidity

Currently, I am working on developing a simple dapp in Truffle. However, I encountered an error when using $.getJSON() function in my app.js file. Below is a snippet of my app.js: App ={ web3Provider: null, contracts: {}, init: function (){ return A ...

Trigger .gif on hover using ng-repeat in AngularJS

Many solutions to this problem involve using jQuery, such as the following examples: Stop a gif animation onload, on mouseover start the activation and Animating a gif on hover. However, I'm interested in achieving the same functionality using Angular ...