访问接口函数内部声明的泛型类型

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

给出以下界面:

export interface MyInterface<T extends Document> {
    foo<D extends Document>(pipeline?: Document[] | undefined): Promise<D[]>;
}

我正在导出一个返回上述接口的函数,如下所示:

export function makeMyObject<T extends Document>(): MyInterface<T> {
    return {
       async foo<D extends Document>(pipeline) {
            console.log(pipeline);
            const d: D[] = [];
            return Promise.resolve(d);
        }
    };
}

但是泛型类型

D
不能在
foo
函数内部使用。 如果我写

async foo<D>(pipeline) { ... }

Typescript 无法识别在

MyInterface
接口内声明的函数,抱怨参数具有
any
类型。

是否可以在

D
函数内部访问
foo
类型并正确定义
MyInterface
内部声明的函数?

typescript typescript-generics
1个回答
0
投票

就目前情况而言,您没有理由在函数中使用任何泛型,因为您没有在任何参数中使用泛型。

所以这些是等价的

export interface MyInterface<T extends Document> {
    foo<D extends Document>(pipeline?: Document[] | undefined): Promise<D[]>;
}

export interface MyInterface {
    foo(pipeline?: Document[] | undefined): Promise<Document[]>;
}

基本上,当您尝试直接从参数推断某些内容时,您只想使用泛型,否则它们毫无用处。

也许你正在尝试这样做?

export function makeMyObject<T extends Document>(options: {
    parameter: T[]
}) {
    return {
       async foo(pipeline?: Document[]): Promise<T[]> {
            console.log(pipeline);
            const d: T[] = [];
            return Promise.resolve(d);
        }
    };
}

如果您尝试从 makeMyObject 参数推断 foo 结果类型。

或者,如果您尝试从 foo 参数类型推断,那么只需这样做

async foo<D extends Document>(pipeline?: D[]): Promise<D[]> {
    console.log(pipeline);
    const d: D[] = []; // Using D[] is allowed here
    return Promise.resolve(d);
}
© www.soinside.com 2019 - 2024. All rights reserved.