Home > Back-end >  How to pass type as parameter?
How to pass type as parameter?

Time:03-09

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;
                    }
}
            }

CodePudding user response:

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;
}

  • Related