What causes an array of type `never[] & number[]` to be generated when using `Object.assign`?

Take a look at this code snippet:

const arr = [1,2,3]
const res1 = arr.slice()
const res2 = Object.assign([],arr)

When using arr.slice() to create a shallow clone, the resulting array res1 will have a type of number[], just like the original arr. However, if you use Object.assign() instead, the array res2 will have a type of never[] & number[].

But why does the type of res2 include never[]? How can it be both number[] and never[] at the same time (using the & operator)?

Answer №1

Consider the nature of Object.assign:

Object.assign<T, U>(target: T, source: U): T & U

In other words, the type returned is the intersection of the objects passed as target and source. When type declarations are not explicitly stated, TypeScript infers the types of the arguments being passed. In the case of `arr`, it correctly infers as `number[]`, but for the first argument/target, since it is an empty array with no elements to infer from, it is inferred as `never[]`, resulting in a return type of `never[] & number[]`.

To achieve the desired result, you can explicitly specify the type of target, like this:

const res2 = Object.assign([] as number[], arr)

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 way to incorporate ControlContainer in an Angular component's unit test?

Is there a way to include ControlContainer in an Angular unit test? The error message I am encountering reads: NullInjectorError: StaticInjectorError(DynamicTestModule)[ChildFormComponent -> ControlContainer]: StaticInjectorError(Platform: core) ...

Is Highcharts-angular (Highcharts wrapper for Angular) compatible with Angular 4?

I have attempted to install various versions of highcharts-angular, ranging from 2.0.0 to 2.10.0. However, I consistently encounter the same error when running the application. The error message states: Metadata version mismatch for module C:/dev/Angular- ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

Implementing Limited Results in Redis FT.SEARCH with TypeScript

Snippet of code: client.ft.SEARCH('license-index-json',"@\\$\\" + ".reservedForApplicationName:GSTest",{ LIMIT: { from: 0, to: 1 } }) Error message: An error occurred when trying t ...

Router-outlet @input decorator experiencing issues with multiple components

Within my router module, I have a route set up for /dashboard. This route includes multiple components: a parent component and several child components. The data I am trying to pass (an array of objects called tablesPanorama) is being sent from the parent ...

Effortlessly sending information to the Material UI 'Table' element within a ReactJS application

I have integrated a materialUI built-in component to display data on my website. While the code closely resembles examples from the MaterialUI API site, I have customized it for my specific use case with five labeled columns. You can view my code below: h ...

Troubleshooting: Angular add/edit form issue with retrieving data from a Span element within an ngFor loop

I am currently working on an add/edit screen that requires submitting a list, among other data. The user will need to check 2-3 checkboxes for this specific data, and the saved record will have multiple options mapped. Here is what the HTML looks like: &l ...

Issue TS2339: The object does not have a property named 'includes'

There seems to be an issue that I am encountering: error TS2339: Property 'includes' does not exist on type '{}'. This error occurs when attempting to verify if a username is available or not. Interestingly, the functionality works ...

Is it possible to leverage ES6 modules within a Node.js application while also debugging it using Visual Studio?

Trying to create a basic node.js module test project using ES6 in Visual Studio 2015 has resulted in build errors, preventing me from running or debugging the application. Could it be that I arrived at the party too soon? I attempted opening and building ...

Looking for a button that can be toggled on and off depending on the input fields

Even after adding useEffect to my code, the button component remains disabled unless the input fields are filled. It never enables even after that. export default function Page() { const [newPassword, setNewPassword] = useState(''); const [conf ...

What causes error TS2345 to appear when defining directives?

Attempting to transition an existing angular application to typescript (version 1.5.3): Shown below is the code snippet: 'use strict'; angular.module('x') .directive('tabsPane', TabsPane) function TabsPane(ite ...

Implementing typing for a module that exports an instance of a particular class

Attempting to create a .d.ts file for the foo-foo-mq module has presented some challenges. Following the documentation, a 'foo-foo-mq' folder was created within the 'typings' directory at the project's root. An index.d.ts file was ...

selectize.js typescript: Unable to access values of an undefined object (reading '0')

I've been working on incorporating selectize.js into my project using webpack and typescript. After installing selectize.js and the necessary types, I added the following to my code: yarn add @selectize/selectize yarn add @types/select2 Within my c ...

Limit the usage of typescript to ensure that references to properties of 'any' object are verified

I'm facing a situation where I have a JS object called myObject, and it is of type any. Unfortunately, I cannot change the type as it's coming from a library. The issue I encounter is that when trying to access a property from myObject, TypeScri ...

Utilize Firebase for Playwright to efficiently implement 'State Reuse' and 'Authentication Reuse'

In my testing environment, I want to eliminate the need for repeated login actions in each test run. My approach involves implementing 'Re-use state' and 'Re-use Authentication', but I've encountered a challenge with Firebase using ...

Unexpected patterns observed when utilizing parent/child routing files

I am working with a Node/Express backend that is implemented using TypeScript. Whenever I make changes to a file and save it, if I test the root route in Postman localhost:8000/, I receive the expected response. However, when I test localhost:8000/user af ...

Utilize Angular2 to dynamically add new routes based on an array register

Currently, I am utilizing Angular2 for the frontend of my project and I am faced with the task of registering new Routes from an array. Within my application, there is a service that retrieves data from a server. This data is then stored in a variable wit ...

Tips on leveraging an attribute for type guarding in a TypeScript class with generics

Is there a way to utilize a generic class to determine the type of a conditional type? Here is a basic example and link to TS playground. How can I access this.b and this.a without relying on as or any manual adjustments? type X<T> = T extends true ...

Discovering the type in Typescript by specifying a function parameter to an Interface

Consider this sample interface: interface MyInterface { x: AnotherThing; y: AnotherThingElse; } Suppose we make the following call: const obj: MyInterface = { x: {...}, y: {...}, } const fetchValue = (property: keyof MyInterface) => { ...

Incorporating Firebase administrator into an Angular 4 project

Currently encountering an issue while trying to integrate firebase-admin into my angular project. Despite my efforts, I am unable to resolve the error that keeps popping up (refer to the screenshot below). https://i.stack.imgur.com/kdCoo.png I attempted ...