[英]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
获取正确的类型?
您不能仅使用变量来执行此操作,您可以使用函数的推理行为来获得所需的行为:
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.