如何创建一个通用类型的函数来映射每个键的返回类型?

huangapple go评论47阅读模式
英文:

How do I make a generic type function to map the return types of each key?

问题

Here is the translation of the provided code snippet:

如果我有

```typescript
type T1 = {
  a: () => string,
  b: () => number
}

type T2 = {
  [P in keyof T1]: ReturnType<T1[P]>
}

那么 T2 是

{
  a: string,
  b: number
}

我如何创建一个通用类型函数来映射返回类型,假设通用类型的每个键都是一个函数?

type MapReturnType<T extends Record<string, ???>> = {
  [P in keyof T]: ReturnType<T[P]>
}

<details>
<summary>英文:</summary>

If I have

type T1 = {
a: () => string,
b: () => number
}

type T2 = {
[P in keyof T1]: ReturnType<T1[P]>
}


Then T2 is

{
a: string,
b: number
}


How do I make a generic type function to map the return types, assuming each key of the generic type is a function?

type MapReturnType<T extends Record<string, ???>> = {
[P in keyof T]: ReturnType<T[P]>
}



</details>


# 答案1
**得分**: 1

你可以使用 `() => any` 作为你拥有的值,因为它是一个函数。

```typescript
type MapReturnType<T extends Record<string, () => any>> = {
  [P in keyof T]: ReturnType<T[P]>
}
英文:

You can use () =&gt; any as the value you have is a function

type MapReturnType&lt;T extends Record&lt;string, () =&gt; any&gt;&gt; = {
  [P in keyof T]: ReturnType&lt;T[P]&gt;
}

huangapple
  • 本文由 发表于 2023年4月17日 11:30:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031539.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定