打字稿中是否有办法获取对象属性函数的返回类型并将其用作另一个对象属性函数的参数的类型?
例如:
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),
}
非常感谢
答案 0 :(得分:2)
如果没有类型参数,则不能使用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),
});