首页 > 解决方案 > TypeScript - 根据另一个函数的返回类型推断函数的参数类型

问题描述

我有一个看起来像这样的界面:

interface Res<R = any> {
    first?(): Promise<R>;
    second(arg: { response: R }): void;
}

当我基于上述接口创建一个普通对象时,响应类型无法正确推断,如下例所示:

const entity: Res = {
    first: () => Promise.resolve({ name: 'Bob' }),
    second: (arg) => {
        console.log(arg.response) // is "any", but should be "{ name: string }"
    }
}

arg.response是否可以根据first()方法返回的内容获得正确的类型?

TS游乐场

标签: javascripttypescripttypes

解决方案


您不能仅使用变量来执行此操作,您可以使用函数的推理行为来获得所需的行为:

interface Res<R = any> {
    first?(): Promise<R>;
    second(arg: { response: R }): void;
}

function createRes<T>(o: Res<T>) {
    return o
}
const entity = createRes({
    first: () => Promise.resolve({ name: 'Bob' }),
    second: (arg) => {
        console.log(arg.response)
    }
})


游乐场链接


推荐阅读