简体   繁体   English

使用本身是泛型的类型专门化泛型 function

[英]Specialize generic function with a type that is itself a generic

In general, "specializing" generic functions in Typescript can be implemented by returning functions:一般来说,Typescript中的“特化”泛型函数可以通过返回函数来实现:

export function twice<T>() {
  return (obj: T): [T, T] => {
    return [obj, obj];
  };
}

interface Bar {
  bar: string;
}

const twiceBar = twice<Bar>();

Here, twiceBar basically is identical to (obj: Foo) => [obj, obj] .这里, twiceBar基本上等同于(obj: Foo) => [obj, obj]

Is it possible to specialize a function with a type that is itself a generic?是否可以将 function 专门化为本身是泛型的类型?

interface Baz<T> {
  baz: T;
}

const twiceBaz = twice<Baz>(); // <--- does not compile

Here, I'd like twiceBaz to be <T>(obj: Baz<T>) => [obj, obj] .在这里,我希望twiceBaz成为<T>(obj: Baz<T>) => [obj, obj] How can that be achieved?怎样才能做到这一点?

What you want to do is twice<Baz<T>> while letting T remain generic.你想要做的是twice<Baz<T>> ,同时让T保持通用。 The function twiceBaz is generic over this T , by specifying it, your problem will be solved. function twiceBaz在此T上是通用的,通过指定它,您的问题将得到解决。

function twiceBaz<T>() {
  return twice<Baz<T>>();
}

You need to specify twiceBaz as a function that calls twice because that's the only way to get a new T generic parameter.您需要将两次Baz 指定为调用twicetwiceBaz ,因为这是获取新T泛型参数的唯一方法。

The signature ends up being exactly the one you want and it works:签名最终正是您想要的签名,并且可以正常工作:

interface Baz<T> {
  baz: T;
}

const twiceBazNumber = twiceBaz<number>();
const numberBaz = {
  baz: 2;
};

console.log(twiceBazNumber(numberBaz)); // [ { baz: 2 }, { baz: 2 } ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM