gpt4 book ai didi

javascript - 如何设置一个工厂函数来实现它在Typescript中生成的类的参数调用签名?

转载 作者:行者123 更新时间:2023-11-30 19:57:43 25 4
gpt4 key购买 nike

我什至不确定我想做的事情是否可行。我正在使用一个为依赖注入(inject)提供装饰器的框架,正确输入下面的代码示例非常困惑:

class Control {
constructor(
options: {
tabIndex?: number
},
callbacks: {
onChange?: (event: any) => void,
}
) {

}
}

@inject(Factory.of(Control))
class Form {
public GetControl: any;
public control: Control;

constructor(GetControl: any) {
this.GetControl = GetControl;
}
build() {
this.control = this.GetControl({tabIndex: 0}, null);
}
}

有没有一种方法可以设置 GetControl 的类型,而不必像这样在 Control 类中复制参数定义:

public GetControl: (
options: {
tabIndex?: number
},
callbacks: {
onChange?: (event: any) => void,
}
) => Control;

最佳答案

从 TypeScript 2.8 开始,我们可以使用剩余参数中的元组(阅读 here)和条件类型(docs)从类中获取 GetControl 的类型。

class Control {
constructor(
options: {
tabIndex?: number
},
callbacks: {
onChange?: (event: any) => void,
}
) {

}
}

// Create a function with the same return type and parameters as a constructor
type Factory<T extends new (...a: any[]) => any> =
T extends new (...a: infer A) => infer R ? (...a: A) => R : never;

class Form {
;
public control: Control;
// Shorthand field definition, same as your code but shorter :)
constructor(public GetControl: Factory<typeof Control>) {
}
build() {
this.control = this.GetControl({ tabIndex: 0 }, null);
}
}

Factory 类型将构造函数转换为具有相同参数的函数。我们这样做的方法是使用条件类型的推理行为。如果 T 扩展了一个构造函数类型(它这样做是因为类型约束),我们要求编译器在 A 中放入一个包含所有参数类型的元组( ...a: infer A) 和 R 构造函数的返回类型(=> infer R,这将是类实例类型)。

使用 AR 我们可以定义想要的函数,返回类型为 R 并且我们将构造函数的参数传播到函数的参数 ((...a: A) => R)

关于javascript - 如何设置一个工厂函数来实现它在Typescript中生成的类的参数调用签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53752649/

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