如果我有一堂课,比如
class Foo<T>{}
如何检查方法中类的实例是什么类型?意思是,类似
public barbaz(){
// Does not work
if(typeof(<T>) === 'number'){}
}
如果我有一堂课,比如
class Foo<T>{}
如何检查方法中类的实例是什么类型?意思是,类似
public barbaz(){
// Does not work
if(typeof(<T>) === 'number'){}
}
您将类型和值混合在一起,但我知道有时此功能很有帮助。但是我们处于语言(JS)的超集,它没有任何所谓的“类型参数”。在某个地方(构造函数、设置器),您必须使用类型为“T”的参数。
像这样的东西:
class Foo<T> {
constructor(public type: T) {}
public barbaz(){
// works
if(typeof this.type === 'number'){}
}
}
这里有解决方法。看下一个例子:
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.
因此,在某种程度上,您调用方法的能力取决于提供的泛型
哟可以在这里阅读更多