Typescript 无法从函数参数中推断泛型类型参数。

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

Typescript can't infer a generic type parameter from function arguments

问题

以下是代码的翻译部分:

type Collection<T = any> = T[]

type CollectionGetter = () => Collection

function collectionProcessor(getter: CollectionGetter) {
  const res = getter();
  // 进行一些处理...
  // 返回相同类型的集合
  return res;
}

// ---

interface Item {
  id: number;
}

const myGetter = () => {
  return [
    {
      id: 1
    },
    {
      id: 2
    },
    {
      id: 3
    }
  ] as Collection<Item>
}

const result = collectionProcessor(myGetter);
// typeof result = Collection<any>
// 期望:Collection<Item>
console.log(result);

希望这个翻译对您有所帮助。

英文:

Consider the following code:

type Collection<T = any> = T[]

type CollectionGetter = () => Collection

function collectionProcessor(getter: CollectionGetter) {
  const res = getter();
  // some processing...
  // return collection of the same type
  return res;
}

// ---

interface Item {
  id: number;
}

const myGetter = () => {
  return [
    {
      id: 1
    },
    {
      id: 2
    },
    {
      id: 3
    }
  ] as Collection<Item>
}

const result = collectionProcessor(myGetter);
// typeof result = Collection<any>
// expected: Collection<Item>
console.log(result);

TS Playground

Typescript can't infer the Collection<T> type parameter from the argument passed to collectionProcessor.

What is the right way to type this example?

I know I can type the processor like this function collectionProcessor<R>(getter: CollectionGetter): Collection<R> and pass the type explicitly collectionProcessor<Item>(myGetter), but that would not be very convenient as the argument is passed down from higher levels of abstraction.

答案1

得分: 2

你漏掉了一些泛型以完成链式。

type CollectionGetter<T> = () => Collection<T>

在这里省略 <T>,你只推断出 any

Playground

英文:

You're missing some generics to complete the chain.

type CollectionGetter&lt;T&gt; = () =&gt; Collection&lt;T&gt;

By omitting &lt;T&gt; here, you were infering only any.

Playground

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

发表评论

匿名网友

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

确定