从通用接口的类型创建通用函数

时间:2019-03-15 23:42:09

标签: typescript generics

我想创建一个泛型函数,该泛型函数使用由其他泛型函数的返回值定义的类型。我有一个返回第一个通用接口的函数,如下所示:

myFunction( request: MyThing ): SpecialInterface<YourThing>

因此,我要使用YourThing来创建新界面,然后可以使用ReturnType帮助器获取返回结果

coolFunction( request: ReturnType<myFunctionType> ): void;

,这给了我其他函数返回的通用接口,但是我不想要SpecialInterface<YourThing>,我想要YourThing,这里是通用类型。

是否可以获取该类型?

2 个答案:

答案 0 :(得分:2)

这是将request的类型解析为YourThing的一种方法。

interface MyThing { 
    y: string;
}

interface YourThing { 
    x: string;
}

interface SpecialInterface<T> { 
    z: T;
}

const myFunction = (request: MyThing): SpecialInterface<YourThing> => {
    return null;
};

type InnerType<T> = T extends SpecialInterface<infer X> ? X : never;

const coolFunction = (request: InnerType<ReturnType<typeof myFunction>>): void => { 
    // do something
}

coolFunction({}); // error
coolFunction({} as MyThing); // error
coolFunction({} as YourThing);

这里是in the TypeScript playground

答案 1 :(得分:0)

您几乎一直都在那,我们只需要访问该字段即可:

function coolFunction(request: (ReturnType<typeof myFunction>)['whatThing']): void {

针对上下文的更完整示例:

interface SpecialInterface<T> {
    whatThing: T;
}

interface YourThing {
    foo: string;
}

interface MyThing {
    bar: string;
}

function myFunction(request: MyThing): SpecialInterface<YourThing> {
    return { whatThing: { foo: "hi" } };
}

type myFunctionType = (ReturnType<typeof myFunction>);

function coolFunction(request: myFunctionType['whatThing']): void {
    // Do something with request, which is of type YourThing!
    console.log(request.foo);
}