typescript - 如何将属性函数的返回类型推断为属性的类型?
问题描述
打字稿中有没有办法获取对象属性函数的返回类型并将其用作另一个对象属性函数参数的类型?
例如:
const request = {
// Infer the return type of this data function as shown to below...
data: () => ({ people: ["bob", "jack"] }),
// The type of `data` parameter should now be an object with people as a prop with the type of string[].
run: (data) => Promise.resolve(data.people),
}
我什至不确定这是否可能,但我得到的最接近的是以下......
interface IRequest<TDataProps = {}> {
data: () => TDataProps,
run: <TReturnRun>(data: TDataProps) => MaybePromise<TReturnRun>;
}
// So can manually provide the type but not inferred...
const request: IRequest<{ people: string[] }> = {
data: () => ({ people: ["bob", "jack"] }),
run: (data) => Promise.resolve(data.people),
}
非常感谢
解决方案
你不能使用IRequest
没有类型参数的类型,除非你希望它使用默认类型,{}
因为你有<TDataProps = {}>
.
但是您可以做的是定义一个类型,然后您可以在函数中使用它来推断泛型类型参数的正确类型。
像这样:
interface IRequest<TDataProps, TReturnRun> {
data: () => TDataProps,
run: (data: TDataProps) => MaybePromise<TReturnRun>;
}
// The simplest example of a function that can correctly infer the types.
const makeRequest = <TDataProps, TReturnRun>(request: IRequest<TDataProps, TReturnRun>) => request;
// Now you can use this function to avoid having to specify the types.
const request = makeRequest({
data: () => ({ people: ["bob", "jack"] }),
run: (data) => Promise.resolve(data.people),
});
推荐阅读
- javascript - 如何连接input和three.js画布?
- android - 将迭代器添加到 id --> R.id.+i+
- c# - C# SOAP Webservice 方法返回 null
- python - Python中的SVD图像重建
- c# - 如何参考签入和第二天结帐时间在sql server中获取日期和时间的总工作时间
- printing - 从服务器上运行的 vb 脚本从 Adobe Reader 打印到特定打印机
- javascript - 谷歌脚本只执行一个功能而不是聊天响应的返回
- c++ - 使用 for 循环创建 QScatterSerie
- javascript - 如何更改字符串输出颜色
- wordpress - Elementor 显示服务器错误(403 错误。)