如何确定一个类中的泛型类型? [英] How to determine the type of generic in a class?

查看:110
本文介绍了如何确定一个类中的泛型类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有诸如此类的课程

If I have a class such as

class Foo<T>{}

如何检查方法中类的实例的类型?意思是类似

How do I check what type the instance of the class is in the method? Meaning, something like

public barbaz(){
  // Does not work
  if(typeof(<T>) === 'number'){}
}

推荐答案

此处是解决方法.看下一个例子:

THere is workaround here. Take a look on next example:

interface HandleNumbers {
  add(arg: number): number
}

interface HandleStrings {
  concat(a: string, b: string): string;
}

class Api {
  add = (arg: number) => arg + 1
  concat = (a: string, b: string) => a.concat(b)
}

interface HandleHttp {
  <T extends void>(): {};
  <T extends string>(): HandleStrings;
  <T extends number>(): HandleNumbers;
}

const handleHttp: HandleHttp = <_ extends string | number>() => new Api();

handleHttp<number>() // you can only call [add] method
handleHttp<string>() // you can only call [concat] method
handleHttp() // unable to call any method

请记住,您生成的JS代码将包含方法 add concat .

Please keep in mind, your generated JS code will contain both methods add and concat.

因此,在某种程度上,您调用方法的能力取决于所提供的泛型

So, in some way, your ability to call methods depends on provided generic

您可以在此处

这篇关于如何确定一个类中的泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆