Issue with Partial utility extension function not functioning as expected

While experimenting with TypeScript in the TS playground, I am attempting to create a small utility function but encountering issues with TypeScript's type checking.
The error message states that my argument is

not assignable to parameter of type 'Partial<this["t"]>'

export function x<T, K extends keyof T, M extends T[K]>(obj: T, prop: K, extension: Partial<M>) {
    obj[prop] = {
        ...obj[prop],
        ...extension
    }
}

type T = {
  a: string,
  b: number
}

class C {
  t: T = { a: 'a', b: 3 }

  constructor() {
    x(this, 't', { b: 42 }) // error is here
  }
}

Is there a workaround for this issue? Perhaps using ThisType? Any suggestions would be appreciated.

Answer №1

I can't quite explain the reason behind this occurrence, but a quick solution is to utilize x(this as C, 't', { b: 42 }).

In addition, I suggest making some adjustments to avoid any unusual bugs:

/** Extract keys of type `T` from object of type `O` */
type KeysOfType<O, T> = {
    [P in keyof O]: O[P] extends T ? P : never;
}[keyof O];

export function x<T, K extends KeysOfType<T, Record<any, any>>>(obj: T, prop: K, extension: Partial<T[K]>) {
    obj[prop] = {
        ...obj[prop], // To prevent errors when obj is not yet initialized
        ...extension,
    }
}

type T = {
  a: string,
  b: number
}

class C {
  v = 3;
  t: T = { a: 'a', b: 3 }
  t2: T = { a: 'a', b: 3 }

  constructor() {
    x(this as C, 'v', { b: 42 });  // Error
    x(this as C, 't', { b: 42 });  // OK
    x(this as C, 't2', { b: 42 }); // OK
  }
}

playground

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 simulate the axios call within my express controller?

My axios call is already separated into a module and tested using mocked axios. However, I am facing a dilemma when it comes to testing the controller that imports this function. I understand that it needs to be mocked, but I am uncertain about the most ef ...

Utilizing React-Input-Mask (written in TypeScript) to conceal Material UI input within Formik forms

Issue with Formik Input and TextField Type Error <InputMask mask="99/99/9999" value={formik.values.phone} onChange={formik.handleChange} onBlur={formik.handleBlur} > {(inputProps: Pro ...

Cloud function encountering error: Unable to connect to localhost. Axios request failing with Error: connect ECONNREF

Error encountered with axios request in a Firebase cloud function. Below is the code snippet: import * as functions from 'firebase-functions'; import axios from 'axios'; export const mobileDoUpdate = functions.firestore.document(&apo ...

What is the best way to show an error message if a TextInput field is left blank?

I'm currently working on a mobile application using react-native, focusing on the login page. My goal is to show an error message below a TextInput field when it's left empty. To achieve this, I've been experimenting with the @react-hook-f ...

Display a semantic-ui-react popup in React utilizing Typescript, without the need for a button or anchor tag to trigger it

Is there a way to trigger a popup that displays "No Data Found" if the backend API returns no data? I've been trying to implement this feature without success. Any assistance would be greatly appreciated. I'm currently making a fetch call to retr ...

What is the process for converting a .ts file to a .js file within a Next.js project for Web worker implementation?

I am currently working on a TypeScript Next.js project: "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint& ...

Angular Typescript Filter failing to connect with service injection

I am having trouble accessing the Constant app within a filter in Angular TypeScript. How can I successfully access a service inside a filter? Module App.Filter { import Shared = Core.Shared; export class MilestoneStatusFilter123 { static $inject = ...

To populate an Ionic list with items, push strings into the list using the InfiniteScroll feature

Looking for help with implementing infinite scroll in a list? I am using the ion-infinite-scroll directive but struggling to push string values into my list. The list contains names of students in a classroom. Can anyone provide guidance on how to push str ...

Unable to load dynamic JSON data in ag-grid for Angular 2

ngOnInit(){ this.gridOptions = {}; this.gridOptions.rowData = []; this.gridOptions.rowData = [ {configName: 1, configName1: "Jarryd", configName2: "Hayne", configName3: "tttttt", configName4: "rrrtttt", configName5:"drrrrrr"}]; } ...

Unable to fetch data from URL in Angular using the HttpClientModule

I have a goal in my application to retrieve data from the following URL and showcase it within the app: https://jsonplaceholder.typicode.com/posts/1 The issue I'm encountering is that the data is not being displayed in my app. The console is showing ...

The seamless fusion of Express with Typescript

Hello and thank you for taking the time to assist me. I recently completed a Cron app using Node.JS. I wanted to add a website hosted by the Node.js server with Express. I developed this TypeScript website in a separate folder, but encountered errors when ...

Discovering different types of navigation in React Navigation using navigationRef

I'm currently working on adding types to my TypeScript version of this function, but I'm facing some difficulties with it. Perusing the React Navigation documentation: // RootNavigation.js import { createNavigationContainerRef } from '@rea ...

The module named "domhandler" does not have an exported member called 'DomElement'. Perhaps you meant to use 'import DomElement from "domhandler"' instead?

I am currently working on a react-typescript project and encountered an error while trying to build it. It seems that I forgot to install dom utils and HTML parser libraries, and now I am facing the following issue when I attempt to run yarn build: ...

Does the Angular2.0 router only function with components, not modules?

Currently in the process of adjusting an existing angular application to integrate with the format of this Starter Project. Within my app module, there exists a submodule (tutorial) structured as follows: https://i.sstatic.net/Q9Dku.png Upon initially acc ...

Can you explain the concept of "Import trace for requested module" and provide instructions on how to resolve any issues that

Hello everyone, I am new to this site so please forgive me if my question is not perfect. My app was working fine without any issues until today when I tried to run npm run dev. I didn't make any changes, just ran the command and received a strange er ...

Utilize dynamic components to load varying data sets multiple times

Is there a way to dynamically load a component multiple times and pass data based on certain values so that it will display with real-time information? I came across an example at the following link: In this example, there is a messageComponent with a "m ...

What are some ways to conceal methods within a class so that they are not accessible outside of the constructor

I am a newcomer to classes and I have written the following code: class BoardTypeResponse { created_on: string; name: string; threads: string[]; updated_on: string; _id: string; delete_password: string; loading: BoardLoadingType; error: Bo ...

acquire tabulations from every single document within the templates on DocuSign

When using Docusign, it is possible to retrieve tabs data for a specific document within a template by specifying the documentId. However, I have not been able to locate a method to obtain tabs data for all documents contained within a template. ...

"Compilation errors encountered when trying to build Typescript within a Azure Function App running in

Currently, I am in the process of deploying to an Azure Function App from a container that resides inside Azure Container Registry. To begin with, I utilized the func init command (selected the typescript option) and incorporated some code using the servi ...

Signature index that allows for distinct types for accessing and setting values

At the moment, it is feasible to have a setter that supports both undefined/null and a getter for non-undefined/non-null values: export interface IProperty<T> { get value(): T; set value(value: T | undefined); } // the following is ok with & ...