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

TS2322: Type '(new () => typeof Rectangle)[]' is not assignable to type 'Rectangle[]'

I have a function that stamps copies of classes. It takes a class and returns as many copies of classes as I specified. But the problem is not in the function but in its signature. To create new classes I need a function new and to connect it I did extends { new(): T }. I need it to return an array of classes with their type, but instead it returns (new () => typeof Rectangle)[] and I can’t figure out what the problem is. Here is the code.

class Rectangle {
    w!: number;
    h!: number;
}
class Circle {
    radius!: number;
}


function stampFigures<T extends { new (): T } >(someClass: T, count: number): T[] {
    let a = []
    for (let i = 0; i < count; i++)
        a.push(new someClass());

    return a;
}

let a: Rectangle[] = stampFigures(Rectangle, 10); //here i need Rectangle[] but i got (new () => typeof Rectangle)[]
let b: Circle[] = stampFigures(Circle, 20) //and here

console.log(a)
console.log(b)

>Solution :

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

You need to infer an instance type of class:

class Rectangle {
  w!: number;
  h!: number;
}
class Circle {
  radius!: number;
}


function stampFigures<
  Klass extends { new(): any }
>(someClass: Klass, count: number) {
  let a: InstanceType<Klass>[] = []
  for (let i = 0; i < count; i++)
    a.push(new someClass());

  return a;
}

let a = stampFigures(Rectangle, 10); //  Rectangle[]
let b = stampFigures(Circle, 20) // Circle[]

console.log(a)
console.log(b)

Playground

YOu can also check my article

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