gpt4 book ai didi

typescript :包装泛型类的函数返回类型

转载 作者:行者123 更新时间:2023-12-04 12:31:42 26 4
gpt4 key购买 nike

我无法使用 Typescript 以通用方式解决这个问题,我将不胜感激任何帮助!

  • 工厂应该部署合约
  • CustomFactory 是一个工厂,应该部署一个 CustomContract(即契约(Contract))
  • MockFactory 应该是所有这些逻辑的包装器

目标就是这样(半伪代码)

interface MockFactory<F extends Factory> extends F {
deploy: (...args: Parameters<F.prototype.deploy>) => MockContract<F.prototype.deploy.returnValue>
}

为了更好地说明问题,我创建了一个 Playground在哪里可以看到错误

最佳答案

刚刚通过使用 ReturnType 和 Parameters 解决了,还需要将接口(interface)转换为类型:

interface Contract {}

interface Factory {
deploy: (...args: any[]) => Contract;
}

class CustomContract implements Contract {}

class CustomFactory implements Factory {
deploy(x: number, y: number): CustomContract {
return {};
}
}

type MockContract<C extends Contract> = Contract & C & {
mockProperty: number;
}

type MockFactory<F extends Factory> = F & {
// deploy should have the parameters of the function deploy inside F (in this case CustomFactory)
// deploy should return a MockContract of the return type of the function deploy inside F (MockContract<CustomContract> in a generic way)
deploy: (...args: Parameters<F['deploy']>) => MockContract<ReturnType<F['deploy']>>
}

const example: MockFactory<CustomFactory> = {} as any;
example.deploy(1, 2);

Updated Playground

关于 typescript :包装泛型类的函数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68595207/

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