简体   繁体   English

如何解开打字稿通用内部类型

[英]How to unwrap a typescript generic internal type

I have a graph of generic classes, where the wrapped type is needed to specify other classes.我有一个泛型类图,其中需要包装类型来指定其他类。

interface Data {
    id: number,
}

class EntityClass<T extends Data> {
    public data;

    constructor(data: T) {
        this.data = data;
    }
}

class Result<T extends Data> {
    public data

    constructor(data) {
        this.data = data;
    }
}

Right now I'm passing both the type ( EntityClass<any> and the internal type ( DataClass ), even though it always matches what would be any here.现在我正在传递类型( EntityClass<any>和内部类型( DataClass ),即使它总是匹配这里的any

function extract<Class extends EntityClass<any>, DataClass extends Data>(
    entity: Class
) : Result<DataClass> {}

Is there a way to "unwrap" the internal type of EntityClass, to avoid passing both?有没有办法“解开”EntityClass 的内部类型,以避免同时传递两者? Here's what I'd like to do:这是我想要做的:

function extract<Class extends EntityClass<InternalClass>>(
    entity: Class
) : Result<InternalClass> {}

This a basic application of conditional types and their inference behavior这是条件类型及其推理行为的基本应用

class EntityClass<T extends Data> {
    public data: T; // T assuming this should be T

    constructor(data: T) {
        this.data = data;
    }
}

type GetDataClass<T  extends EntityClass<any>> = T  extends EntityClass<infer U > ? U: never;
function extract<Class extends EntityClass<any>>(
    entity: Class
) : Result<GetDataClass<Class>> { return null as any}

Or you can also do it with a type query as well, but that means you will be tied to the data field, the conditional type will extract the generic type based on structure without you having to specify a particular field.或者,您也可以使用类型查询来执行此操作,但这意味着您将绑定到data字段,条件类型将根据结构提取通用类型,而无需指定特定字段。

function extract<Class extends EntityClass<any>>(
    entity: Class
) : Result<Class['data']> { return null as any}

You can read more about type queries and conditional types here您可以在此处阅读有关类型查询和条件类型的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM