如何在泛型函数中重用泛型静态方法的参数?

问题描述 投票:0回答:1

这里我尝试在通用函数上重用

Omit<T, 'id'>

class Model{
   static func<T extends Model>(a: Omit<T, 'id'>): number{
        return 0;
    }

    id = 0;
    title = 'test';
}

class Child extends Model{
    child = true;
}


function test<T extends typeof Model>(model: T, data: Parameters<T.func<InstanceType<T>>>[0]) : T {
    return {} as T;
}

游乐场

使用

T.func
给出:

Cannot access 'T.func' because 'T' is a type, but not a namespace. Did you mean to retrieve the type of the property 'func' in 'T' with 'T["func"]'?(2713)

使用

T['func']
给出

Parameter 'InstanceType' implicitly has an 'any' type.

有什么方法可以在不引入通用外部类型的情况下重用参数?

typescript
1个回答
0
投票

我认为您使用

InstanceType
不正确。

class Model {
    static func<T extends Model>(a: Omit<T, 'id'>): number {
        return 0;
    }

    id = 0;
    title = 'test';
}

class Child extends Model {
    child = true;
}

function test<T extends typeof Model>(
    model: T,
    data: Parameters<T['func']>[0]
): InstanceType<T> {
    return {} as InstanceType<T>;
}
© www.soinside.com 2019 - 2024. All rights reserved.