【问题标题】:how to accept a generic tuple as a parameter and return a genaric containing the generic types如何接受泛型元组作为参数并返回包含泛型类型的泛型
【发布时间】:2020-09-30 07:04:52
【问题描述】:

所以现在 typescript 4 已经出来了,我希望这会更容易,但我仍然没有找到实现这一点的方法。

我正在尝试创建一个函数,该函数接受一个包含特定泛型的元组并返回一个泛型返回包含值。

interface STORE<T> {
  data: T;
}

const merge = <U extends any, T extends readonly STORE<U>[]>(values: T): STORE<U[]> =>
  values.reduce<STORE<U[]>>(
    (acc, item) => {
      return { data: [...acc.data, item.data] };
    },
    { data: [] },
  );

例如调用它应该会导致以下结果

assert(merge([{ data: 'test' }, { data: 2 }]), { data: ['test', 2]});

然而,这会将值返回为STORE&lt;unknown[]&gt;,而不是维护输入中的类型。

【问题讨论】:

  • 请在 TS 操场上发布完整示例
  • 如果没有minimal reproducible example 至少包括TYPEONETYPETWO 的玩具定义,就很难回答这个问题。正确的答案可能是在函数中只使用一个类型参数,但如果没有可重现的示例,我将无法验证任何内容。
  • @captain-yossarian 我已经更新了要提供的问题和示例
  • @jcalz 我已经更新了要提供的问题和示例
  • 我认为这些答案可能对您有所帮助:1)stackoverflow.com/questions/63325817/… 2)stackoverflow.com/questions/50374908/…

标签: typescript


【解决方案1】:

why does typescript function parameter type infer failed?

使用T &amp; (constraint of T) 可以解决您的问题:

const merge = <U extends any, T extends readonly STORE<U>[]>(
  values: T & readonly STORE<U>[],
         // ^ here to ---- here ^
): STORE<U[]> => values.reduce<STORE<U[]>>((acc, item) => {
    return {data: [...acc.data, item.data]};  
  }, {data: []})


interface STORE<T> {
  data: T;
}

【讨论】:

  • 这不适用于上面的示例,我只是在数组的第二个条目上得到Type 'number' is not assignable to type 'string'.ts(2322)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多