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

How to pass type as parameter?

I have the duplicate part of code that I want to move in separated function:

 for (var i = allActions.length - 1; i >= 0; i--) {
                if (allActions[i] instanceof EditablePolygon) {
                    this.currentAction = allActions[i];
                    break;
                }
            }

This code depends on type EditablePolygon. Could I pass this type as parameter in function?

function iterate(type: T) {
     for (var i = allActions.length - 1; i >= 0; i--) {
                    if (allActions[i] instanceof T) {
                        this.currentAction = allActions[i];
                        break;
                    }
}
            }

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 :

Yes, you can. Consider the following:

TS Playground

type Constructor<Params extends readonly any[] = readonly any[], Result = any> =
  new (...params: Params) => Result;

function findInstance <Ctor extends Constructor>(array: readonly unknown[], constructor: Ctor): InstanceType<Ctor> | undefined {
  for (const value of array) {
    if (value instanceof constructor) return value;
  }
  return undefined;
}

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