Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

typescript - custom generic instanceof function

I am performing an instanceof check in *ngIf.

 <span *ngFor="let element of elements"> 
   <app-text *ngIf="element instanceof BlueElement"></app-text>
 </span>

Unfortunately, instanceof cannot be used, because it is defined by javascript.

Therefore I created my own instanceOf method:

  instanceOf<T,C>(value:T,clss:C){
    if (value instanceof C){
      return true;
    }else{
      return false;
    }
  }

I am getting an error; C is only defined as a type, but is being used as a value here.

How should I rewrite the generic instanceOf() function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can only use instanceof on a constructor value.

That means it must be a constructor value as opposed to just any old object. TypeScript only requires the constructor property of a class to be a Function, so at the very least you need to specify that C extends Function. If you want to be safer, restrict C to actual constructor functions whose singatures are like new(...args: any[])=>any.

It also means it must be a constructor value as opposed to its type. The value is clss, and its type is C. As pointed out by @vu1p3n0x, you should writeinstanceof clss. You can't write instanceof C, since C is just a type and it doesn't even exist at runtime.

Putting that together:

function instanceOf<T, C extends new (...args: any[]) => any>(value: T, clss: C): boolean {
  return value instanceof clss;
}

As an aside, note that in JavaScript value instanceof clss evaluates either true or false. So you can just return it instead of checking it with if.

Hope that helps; good luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...