【问题标题】:using generics in TypeScript在 TypeScript 中使用泛型
【发布时间】:2020-04-11 04:57:35
【问题描述】:

我创建了这个在 TypeScript 中使用泛型的类

export class ModelTransformer {

    static hostelTransformer: HostelTransformer;

    static fromAtoB(instance: T): U {
        if (instance instanceof HostelType) {
            return ModelTransformer.hostelTransformer.fromAtoB (instancet);
        }
    }

}

但是当我编译它时,我有那些编译错误:

src/model/transformer/model.transformer.ts:11:47 - 错误 TS2304:找不到名称“T”。

11     static fromAtoB(instance: T): U {

src/model/transformer/model.transformer.ts:11:51 - 错误 TS2304:找不到名称“U”。

11     static fromAtoB(instance: T): U {

我已经尝试了建议的解决方案,但是我遇到了这个错误:

错误 TS2366:函数缺少结束返回语句并且返回类型不包括“未定义”。

【问题讨论】:

  • 除了 Bauke 的回答:例如,您需要将方法的返回类型更改为 U | void,因为如果 instance 不是 instanceof HostelType,它不会返回任何内容。

标签: javascript node.js typescript


【解决方案1】:

您需要按照in the handbook 的描述定义一个“类型变量”,如下所示:

static fromAtoB<T, U>(instance: T): U {
    if (instance instanceof HostelType) {
        return ModelTransformer.hostelTransformer.fromAtoB (instancet);
    }
}

【讨论】:

  • 这是正确的答案,但是因为U 没有下限并且没有作为类型参数提供给fromAtoB,所以它仍然会出现类型错误,除非fromAtoB 的返回类型是 anynever 或另一个无下界类型参数。 (并不是说 Typescript 目前支持类型变量的下限。)
猜你喜欢
  • 1970-01-01
  • 2020-07-23
  • 2019-03-08
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2019-06-27
  • 2018-06-25
  • 2019-09-28
相关资源
最近更新 更多