自定义通用函数实例

自定义通用函数实例

本文介绍了自定义通用函数实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 *ngIf 中执行 instanceof 检查.

I am performing an instanceof check in *ngIf.

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

很遗憾,不能使用instanceof,因为它是由javascript定义的.

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

因此我创建了自己的 instanceOf 方法:

Therefore I created my own instanceOf method:

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

我收到一个错误;C 仅定义为类型,但在此处用作值.

我应该如何重写通用的 instanceOf() 函数?

How should I rewrite the generic instanceOf() function?

推荐答案

您只能使用 instanceof 在构造函数值上.

You can only use instanceof on a constructor value.

这意味着它必须是一个构造函数值,而不是任何旧对象.TypeScript 只要求类的constructor 属性是Function,所以至少你需要指定C extends Function.如果您想更安全,请将 C 限制为实际构造函数,其特征类似于 new(...args: any[])=>any.

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.

这也意味着它必须是一个构造函数 value 而不是它的 type.值为clss,类型为C.正如 @vu1p3n0x 所指出的,您应该编写instanceof clss.你不能写instanceof C,因为C 只是一种类型,它在运行时甚至不存在.

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.

综合起来:

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

顺便说一句,请注意在 JavaScript 中,value instanceof clss 计算 truefalse.所以你可以直接返回它而不是用 if 来检查它.

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!

这篇关于自定义通用函数实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:24