gpt4 book ai didi

typescript - 使用 typeof 作为参数类型

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

假设我有一个类:

public class A {
foo: string;
}

我如何定义一个函数以便它接受类的类型并返回它的一个实例?像这样:

function bar<T>(c: typeof T): T {
return new c();
}

const a: A = bar(A);

最佳答案

TypeScript 文档实际上有 an example在泛型中使用类类型:

When creating factories in TypeScript using generics, it is necessary to refer to class types by their constructor functions. For example,

function create<T>(c: {new(): T; }): T {
return new c();
}

new() 是一个 constructor function

关于typescript - 使用 typeof 作为参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56429380/

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