The setter does not have a specified type for the proxy property (illustrated with a minimal repro

When using TypeScript 4.5.4, an error message

Type 'any' is not assignable to type 'never'.(2322)
is being thrown for versions 1, 2, 3, and 4 of the code snippet provided below or accessible in the TypeScript playground). Interestingly, no error is reported for versions 5 and 6. Removing either the num or str property eliminates all errors.

Can someone provide insight into this behavior?

const myObj = {
  num: -1,
  arr: [1, 2, 3],
  str: '',
};

const proxy = new Proxy(myObj, {
  set(target, prop: keyof typeof myObj, value) {
    /* none of these works */
    // Ver. 1
    if (prop in target) target[prop] = value;
    // Ver. 2
    target[prop] = value;
    // Ver. 3
    target[prop as keyof typeof myObj] = value;
    // Ver. 4
    switch (prop) {
      case 'num':
      case 'str':
        target[prop] = value;
        break;
    }

    /* while these works */
    // Ver. 5
    switch (prop) {
      case 'num':
        target[prop] = value;
        break;
      case 'str':
        target[prop] = value;
        break;
    }
    // Ver. 6
    switch (prop) {
      case 'num':
        target[prop] = value;
        break;
      default:
        target[prop] = value;
        break;
    }

    return true;
  },
});

console.log('proxy : ', proxy);

Answer №1

Summary

When writing in TypeScript, type intersection is generated.

Details

This excerpt is a reproduction of the response found in the official repository microsoft/TypeScript#47295. This feature functions as intended.

In the majority of cases, the type assigned to prop does not narrow down from

"num" | "str" | "arr"
; because you are writing to target[prop], rather than reading from it, this results in an intersection (not a union) of all possible types it could represent. If there is no overlap, the intersection reduces to never, as there is no feasible value that satisfies all options.

This response has been provided to address and close the query.

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 correct way to assign multiple types to a single entity in TypeScript?

(code at the end) While attempting to write section.full.link, I encountered the following error: Property 'link' does not exist on type 'SectionSingle | SectionTitle | SectionHeaderMedia'. Property 'link' does not exist on ...

When attempting to utilize the Next.js Head component in a location other than _document, the page experiences

Currently, I am in the process of integrating Next.js with Typescript and Material UI. Despite the abundance of tutorials available online for setting up Next.js with Material UI, I have encountered a commonality among them where they all provide identical ...

What is the best way to incorporate a string value from an external file into a variable in TypeScript without compromising the integrity of special characters?

I am encountering an issue with importing a variable from a separate file .ts that contains special characters, such as accents used in languages like French and Spanish. The problem I am facing is that when I require the file, the special characters are ...

Importing custom pipes in Angular 2 becomes a bit tricky when working with data grouping

As a newcomer to Angular JS, I have recently started using Angular 2 for a project of mine. Here is an example of my JSON data: "locations": [ { "id": "ASS", "name": "test center", "city": "Staten Island", "zip": ...

Enforce directory organization and file naming conventions within a git repository by leveraging eslint

How can I enforce a specific naming structure for folders and subfolders? I not only want to control the styling of the names (kebab, camel), but also the actual names of the folders and files themselves. For example, consider the following paths: ./src/ ...

The transformation from className to class attribute does not occur for custom elements in JSX

I recently encountered an issue with one of my React components where the "className" attribute was being converted to "classname" in the resulting HTML, instead of the expected "class" attribute. The component had a custom element definition as follows: ...

The Static Interface Binding in TypeScript

I have inquired about how to extend the static functionality of existing objects in JavaScript (using TypeScript). In all examples provided here, I am utilizing Object The code below showcases a polyfill definition for ECMAScript's Object.is function ...

Capturing user audio on the client side with Angular

Is there a built-in feature in Angular to record client-side audio input? I have attempted using the p5 library, but it is encountering integration problems. ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

Problems arise in React due to toaster interfering with spying on the 'useState' function

Having an issue with my notifications component while running tests using jest mock implementation on useState. Notifications.tsx import { Toaster } from "react-hot-toast"; export const Notifications = () => { return ( <Toaster ...

Adding URL path in Angular 7's .ts file

I currently have the following code in my component's HTML file: <button mat-flat-button class="mat-flat-button mat-accent ng-star-inserted" color="accent" (click)="playVideo(video)"> <mat-icon [svgIcon]="video.type === 'external' ...

Exploring Typescript: Simulating Nested Classes and Accessing Private Members

Previous solutions regarding typescript and nested classes often recommended utilizing the declaration merging feature of the language. I've experimented with this approach using the code snippet below, which functions correctly but triggers a compile ...

The directive [ngTemplateOutet] is functioning properly, however, the directive *ngTemplateOutlet is not functioning as expected

I have been struggling to create a component using ngTemplateOutlet to select an ng-template, but for some reason *ngTemplateOutlet is not working in this case (although [ngTemplateOutlet] is functioning correctly). Below is the code I am currently using: ...

There is no matching overload for this call in React Native

I am working on organizing the styles for elements in order to enhance readability. Here is the code I have written: let styles={ search:{ container:{ position:"absolute", top:0, }, } } After defining the s ...

Bringing in a service from a different module in NestJS

Having an issue trying to utilize the surveyService within the voteOptionRepository. When attempting to use the route, the console displays: TypeError: this.surveyService.getSurveyById is not a function Below is my SurveyModule setup: @Module({ im ...

The issue of resolving custom paths imports in Typescript has been a persistent challenge for developers

Currently, I am developing a project in PHP and utilizing Typescript. I aim to follow a monorepo pattern similar to what NX offers. However, I am facing challenges when attempting to compile typescript for each of my apps. Here is the current structure of ...

Error: Unable to locate the type definition file for the '@babel' package

I am currently working on a new project and here is the content of my package.json file. { "name": "dapp-boilerplate", "version": "1.0.0", "main": "index.js", "license": "MI ...

A step-by-step guide on setting up a database connection with .env in typeorm

I encountered an issue while attempting to establish a connection with the database using ormconfig.js and configuring .env files. The error message I received was: Error: connect ECONNREFUSED 127.0.0.1:3000 at TCPConnectWrap.afterConnect [as oncomplete] ( ...

The index.ngfactory.ts file threw an unexpected token error, indicating that an appropriate loader may be necessary to handle this specific file

I've spent several hours trying to troubleshoot this persistent error, exhausting all online resources for solutions. The issue arises consistently with every module of Angular Material only during the build process using --env.prod. The webpack confi ...

Dealing with enum values in Jest tests when using Prisma can be tricky. The error message "Group[] not assignable to

Here is an example of my prisma postgresql schema: model User { id Int @id @default(autoincrement()) uuid String @db.Uuid createdat DateTime @default(now()) @db.Timestamp(6) updatedat DateTime @updatedAt first ...