What's the issue with Typescript Generics?

I'm having trouble compiling this code snippet:

type F<A> = (a:A)=>A;

class CLAZZ<S extends { [k: string]: any }, K extends keyof S = keyof S>{
  constructor(a:S){
    this._o=a;
  }
  _o:S;
  set(k:K, f:F<S[K]>){
     f(this._o[k]);
  }
}

type O = {
  pippo: number,
  pluto: string | null,
  paperino: {[k:string]:boolean}
}

let o = new CLAZZ<O>({"paperino":{}, pluto:null, pippo:1});

o.set("paperino", (paperino)=>({...paperino, "ciccio":true}))

playground

The error occurs on the last line:

Spread types may only be created from object types.

This is because the 'paperino' argument is inferred as

(parameter) paperino: string | number | { [k: string]: boolean; } | null

when I am expecting just

{ [k: string]: boolean; }

Even forcing the parameter type results in an error:

o.set("paperino", (paperino: {[k:string]:boolean})=>({...paperino,"ciccio":true}))

Argument of type '(paperino: { [k: string]: boolean; }) => { ciccio: true; }' is not assignable to parameter of type 'F<string | number | { [k: string]: boolean; } | null>'. Types of parameters 'paperino' and 'a' are incompatible. Type 'string | number | { [k: string]: boolean; } | null' is not assignable to type '{ [k: string]: boolean; }'. Type 'null' is not assignable to type '{ [k: string]: boolean; }'.

Is there a solution other than using "any"?

Answer №1

If you simply shift the key generic over to the set method, everything should fall into place seamlessly: interactive platform

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

Retrieving selected values from an ngx dropdown list

I am having trouble implementing ngx dropdown list in this way: <ngx-dropdown-list [items]="categoryItems" id="categoriesofdata" [multiSelection]="true" [placeHolder]="'Select categories'"></ngx-dropdown-list> ...

typescript error: passing an 'any' type argument to a 'never' type parameter is not allowed

Encountering an error with newUser this.userObj.assigned_to.push(newUser);, receiving argument of type 'any' is not assignable to parameter of type 'never' typescript solution Looking for a way to declare newUser to resolve the error. ...

A guide on capturing the response in the POST method within Angular 7

I'm currently working with Angular 7 and I need a way to know if the data has been successfully saved or not. Within my web service code, I have designated "Success" as the status when data is saved correctly, and "Unsuccessful" if the data is not sa ...

Angular binding allows for seamless connection of objects to input fields

Trying to establish a connection between a Company object in my component and the view has proved to be more challenging than expected. While I didn't encounter any issues doing this in AngularJS, attempting it in Angular 2 resulted in an error. View ...

Named functions in Typescript within functional components are the best practice for improving

How can I implement handleFoo using MyType['foo']? type MyType { foo: () => void } const Comp: React.FunctionComponent<{}> = () => { function handleFoo() {} return ... } I'm looking for a solution that doesn't inv ...

Trying to add an item to a TypeScript nested array causes an issue: unable to access property 'push' because it is undefined

For a while now, I've been searching on SO trying to find a solution to my issue. It seems that my code isn't as simple as just "push object into array." In my interface, I have a "Year" property typed with another interface as an array: exp ...

Checking an Angular 2 Component with Constructor Argument

Imagine having an Angular 2 Component containing two input parameters: @Component{... (omitted for clarity)} export class SomeComponent { @Input() a: number @Input() b: number } When needing to test this component, the process typically involves someth ...

Can an object type be partially defined?

Here is a similar scenario: function(param1, { knownParam1, ...opts }) To better describe param1 and knownParam1, perhaps something like this could work: type Param2 = { knownParam1: string, ...otherParams: any } type Parameters = { param1: str ...

Typescript is not in the business of typecasting

Trying to invoke a function from an object in the React state //currentUser is of type User this.state.currentUser.rankUp() This triggers an error message this.state.currentUser.rankUp is not a function. Strangely, creating a new user object allows me to ...

Implementing TypeScript for augmented styling properties in a component - a guide

I have custom components defined as follows: import React from 'react'; import styled from '../../styled-components'; const StyledInput = styled.input` display: block; padding: 5px 10px; width: 50%; border: none; b ...

I have successfully implemented useLazyQuery in a functional component, but now I am looking to integrate it into a class component. Can you provide guidance on how to achieve

Recently, I encountered an issue with my functional component that contains 3 checkboxes and 1 button. I utilized the useLazyQuery hook to ensure that my query was only sent upon clicking the button. However, a major drawback is that my component re-rend ...

Is there a way to include two objects in an Angular2 post request?

This piece of code is giving me trouble: On the client side (using Angular 2) saveConfig(configType: ConfigTypes, gasConfigModel: GasConfigModel): any { console.info("sending post request"); let headers = new Headers({ 'Content-Type& ...

Type of React.Component that is not specific to any particular example

What is the standard type of a React Component? Examples of component classes include: export class MaskCompanyList extends React.Component<MaskCompanyListProps, MaskCompanyListState> { public render() { ... } } export class MaskPe ...

Implement Cross-Origin Resource Sharing in Angular frontend

I am facing an issue with two microfrontends running on different ports (4200 and 4201) where one frontend is unable to access the translation files of the other due to CORS restrictions. To overcome this obstacle, I created a custom loader in my code that ...

Dynamic property access using optional chaining in JavaScript

My attempt to utilize optional chaining, a feature provided by TypeScript for safely accessing dynamic properties, seems to be invalid. export const theme = { headers: { h1: { }, h6: { color: '#828286' }, }, } console.in ...

Exploring the concept of nested arrays in Angular 2 using Typescript

I'm exploring the possibility of defining an array in Angular 2 that contains multiple other arrays within it. To clarify, here's what I had initially: export class PaymentDetails { account: any[]; bpNumber: number; } The issue with t ...

Utilize a dynamically defined union type to create a versatile callback function

I'm currently working on creating a message subscription function. A basic version without types is shown below: function createMessage(message) { postMessage(message) } function addSubscriber(messageType, callback) { handleNewMessage(message =&g ...

How to update the tsconfig.json file within a VS2019 project using MSBuild?

I am working with a Visual Studio solution that contains multiple tsconfig.json files and I would like them to have different behaviors in production. My plan is to create two additional files for this purpose: tsconfig.json will contain the default sett ...

In Typescript, the use of an array as a class member is not defined

I'm having trouble adding an array as a class member in my Typescript code. When I try to access it in a certain function, I keep getting an error saying it's undefined. What am I doing wrong? .html <button id="storePersonBtn"> .ts exp ...

Embed the value of an array in HTML

Upon running console.log, the data output appears as follows: {TotalPendingResponseCount: 0, TotalRequestSendCount: 1, TotalRequestReceivedCount: 1, TotalRequestRejectCount: 3} To store this information, I am holding it in an array: userData : arrayResp ...