typescript - 如何将属性函数的返回类型推断为属性的类型?

标签 typescript typescript-generics

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

Playground link

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

相关文章:

javascript - 如何使用 Typescript 处理可选函数参数?

javascript - 如何允许字段未定义,同时不允许使用 Yup 进行类型强制?

angular - 如何从数组列表中删除数据 - NGXS 状态管理

typescript - 创建具有其他类型和其他可选属性的通用属性的类型

Typescript:是否可以确保键和内部值是相同的字符串?

typescript - typescript 中的嵌套泛型

javascript - 将一个 typescript 文件导入另一个用于浏览器的 typescript 文件

javascript - Angular2 中的响应式(Reactive)选择

typescript :使用泛型函数获取嵌套对象的值

typescript - 在 TypeScript 中,如何获取值为给定类型的对象类型的键?