gpt4 book ai didi

javascript - 在 TypeScript 中使用泛型

转载 作者:行者123 更新时间:2023-12-02 22:15:27 25 4
gpt4 key购买 nike

我创建了这个与 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 - error TS2304: Cannot find name 'T'.

11     static fromAtoB(instance: T): U {

src/model/transformer/model.transformer.ts:11:51 - error TS2304: Cannot find name 'U'.

11     static fromAtoB(instance: T): U {

我已经尝试了建议的解决方案,但出现了此错误:

error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

最佳答案

您需要按照 in the handbook 的描述定义一个“类型变量” ,像这样:

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

关于javascript - 在 TypeScript 中使用泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59395421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com