gpt4 book ai didi

generics - 将泛型运算符 与 FunctionConstructor 连接起来

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:21 26 4
gpt4 key购买 nike

我有 TS 函数,它将 JSON 反序列化为某种类型/对象。你给它一个类型的构造函数,它会尝试从 JSON 重建该类型。

看起来像这样。

export function deserializeJSON<T>(JSONString: string, type?: FunctionConstructor, ...

我想表达,那个论点type: FunctionConstructor<T> 类型的构造函数, 这是否可以通过一些表达来实现?

更新

deserializeJSON 的调用示例

const serializedDate = JSON.stringify(new Date);
const deserializedDate = deserializeJSON<Date>(serializedDate, Date);

编辑

我刚刚发现,FunctionConstructor表示 Function 的构造函数,所以最好将参数标记为 type作为type: Function ,因为所有构造函数都是函数,但是我无法实例化 new type无需将类型转换为 <any> .我想表达类似 <T>.constructor 的东西.

编辑

我已经定义了接口(interface):

interface Constructor<T> extends Function{
new (): T;
new (...args: Array<any>): T;
(...args: Array<any>): T;
prototype: T;
}

这基本上是通用的 newable Function , 但这种类型是 “...不可分配给 DateConstructor 类型的参数” 或任何其他类型的构造函数,因此最好保留 type: Function ,因为它接受所有构造函数。

最佳答案

回答我自己的问题。

这个接口(interface)需要更多的测试,但它似乎工作:

interface Constructor<T> extends Function {
new (): T;
new (...args: Array<any>): T;
prototype: T;
}

关于generics - 将泛型运算符 <T> 与 FunctionConstructor 连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38783925/

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