首页 > 解决方案 > 如何将属性函数的返回类型推断为属性的类型?

问题描述

打字稿中有没有办法获取对象属性函数的返回类型并将其用作另一个对象属性函数参数的类型?

例如:

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),
}

非常感谢

标签: typescripttypescript-generics

解决方案


你不能使用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),
});

游乐场链接


推荐阅读