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),
});
关于typescript - 如何将属性函数的返回类型推断为属性的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63808084/