Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Weird typescript behavior

export class Attributes<T> {
    constructor(private data: T) {}

    get<K extends keyof T>(key: K): T[K] {
        return this.data[key];
    }

    set(update: T): void {
        Object.assign(this.data, update);
    }
}

Screenshot of an error
Error

and text version

No overload matches this call.
  Overload 1 of 4, '(target: {}, source: T): {} & T', gave the following error.
    Argument of type 'T' is not assignable to parameter of type '{}'.
  Overload 2 of 4, '(target: object, ...sources: any[]): any', gave the following error.
    Argument of type 'T' is not assignable to parameter of type 'object'.ts(2769)
Attributes.ts(1, 25): This type parameter might need an `extends {}` constraint.
Attributes.ts(1, 25): This type parameter might need an `extends object` constraint.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As error says:

number.ts(1, 25): This type parameter might need an `extends object` constraint.

So you should constraint T to extend the object, which will means that it is not a primitive:

class Attributes<T extends object> {
  constructor(private data: T) {}

  get<K extends keyof T>(key: K): T[K] {
    return this.data[key];
  }

  set(update: T): void {
    Object.assign(this.data, update); // no error
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading