[英]using generics in TypeScript
I have created this class that works with generics in TypeScript我创建了这个类,它可以在 TypeScript 中使用泛型
export class ModelTransformer {
static hostelTransformer: HostelTransformer;
static fromAtoB(instance: T): U {
if (instance instanceof HostelType) {
return ModelTransformer.hostelTransformer.fromAtoB (instancet);
}
}
}
But when I compile it I have those compilation errors:但是当我编译它时,我有那些编译错误:
src/model/transformer/model.transformer.ts:11:47 - error TS2304: Cannot find name 'T'.
src/model/transformer/model.transformer.ts:11:47 - 错误 TS2304:找不到名称“T”。
11 static fromAtoB(instance: T): U {
src/model/transformer/model.transformer.ts:11:51 - error TS2304: Cannot find name 'U'.
src/model/transformer/model.transformer.ts:11:51 - 错误 TS2304:找不到名称“U”。
11 static fromAtoB(instance: T): U {
I have tried the solution proposed, but then I have this error:我已经尝试了建议的解决方案,但后来出现此错误:
error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
错误 TS2366:函数缺少结束 return 语句并且返回类型不包括“未定义”。
You need to define a "type variable" as described in the handbook , like so:您需要按照手册中的描述定义一个“类型变量”,如下所示:
static fromAtoB<T, U>(instance: T): U {
if (instance instanceof HostelType) {
return ModelTransformer.hostelTransformer.fromAtoB (instancet);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.