繁体   English   中英

TypeScript - 根据来自另一个 function 的返回类型推断函数的参数类型

[英]TypeScript - infer function's argument type based on return type from another function

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

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

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

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

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

TS游乐场

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

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)
    }
})


游乐场链接

暂无
暂无

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

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