javascript - 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()
方法返回的内容获得正确的类型?
解决方案
您不能仅使用变量来执行此操作,您可以使用函数的推理行为来获得所需的行为:
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)
}
})
推荐阅读
- php - 如何使表正确更新数据库中的 otp 代码?
- hyperledger-fabric - 将外部 node.js 包包含到 Hyperledger Fabric 事务处理器函数中的替代方法
- java - 在 Spring 服务中,我应该在方法末尾设置 null 还是空列表以节省内存?
- android - Android:可点击的 TextView 链接/按钮
- javascript - 如何打破while循环和if语句?
- javascript - 我正在 IFRAME 中打开外部网站。如何捕获在 Iframe 中的外部网站中单击的确切链接?
- javascript - 带有 JSON 数据的动态图表 - CanvasJS
- docker - Kubernetes 部署容器后不会启动服务
- php - 加载时执行 PHP 函数时 HTML 不呈现
- c# - 暂停后台工作人员,直到用户确认取消