如何在打字稿中检测带有泛型的 class 实例

How can I detect a class instance with generics in typescript

我正在尝试创建一个带有两个参数的函数,第一个是 class 引用,第二个是只有一个参数的函数,该参数是 class 引用的一个实例并且输出是特定类型。 我尝试了下面的代码,但是打字稿显示了 p 的未知类型,尽管我希望 p 是 Pair 的一个实例。

interface Point{
    x: number
    y: number
}
class Pair{
    key = 0
    value = 0
}
function set<Class extends { new (): Type }, Type>(
    inputClass: Class,
    constructor: (o: Type) => Point) {
    //implementation...
}
set(Pair, p => ({x: p.key, y: p.value}))
// Typescript says:
// (parameter) p: unknown
// Object is of type 'unknown'.(2571)

我想让打字稿知道 p 必须是 Pair 的一个实例


我能够使用 java 泛型实现,但我仍然无法在打字稿中复制。按照代码:

public <K extends Pair, T extends Class<K>> void setRenderer(T classe, Function<K, Point> constructor){
    //implementation
}

我不太确定你为什么需要类这里。

您可以通过接口实现您想要的,如下所示:

interface Point{
    x: number
    y: number
}

interface Pair{
    key:number
    value:number
}
const instance: Pair = {
    key : 0,
    value : 0
}

function set(value: Pair):Point {
    return  ({x: value.key, y: value.value})
}

Playground

或者,如果您确实想要 类,您可以执行以下操作:

Class Playground

这应该有效:

function set<C>(
    inputClass: new ()=>C,
    constructor: (o: C) => Point) {
    //implementation...
}

Typescript Playground

泛型不是这样工作的,类型推断不是这样的。

简单的解决方案:

interface Point{
    x: number
    y: number
}
class Pair{
    key = 0
    value = 0
}
declare function set<Type>(constructor: (o: Type) => Point): void;

set<Pair>(p => ({ x: p.key, y: p.value }))

或者如果你真的想传入 class:

interface Point{
    x: number
    y: number
}
class Pair{
    key = 0
    value = 0
}
function set<Type>(
    inputClass: { new (): Type },
    constructor: (o: Type) => Point) {
    //implementation...
}
set(Pair, p => ({ x: p.key, y: p.value }))