How can I call a generic function with just one generic parameter when the second one is needed on the fly?

∥☆過路亽.° 提交于 2020-07-23 06:37:44

问题


I have a generic function with two parameters. The second one is based on the value of first parameter.

The code works with just one type variable but when I add another one, cannot call the function.

This works perfectly:

type Event<T> = T extends 'string' ? string : number;
type input = 'string' | 'number';

function test<U extends input>(module: U, event: Event<U>) {
  //...
}

//No errors
test('number', 2);

// Generates error as expected
test('string', 2);

But when another generic variable is needed, we have error:

type Event<T> = T extends 'string' ? string : number;
type input = 'string' | 'number';

function test<T, U extends input>(module: U, event: Event<U>) {

  // The subject factory returns a new Rxjs Subject
  return subjectFactory<T>(module + '-' + event);
}

// Works without any generic parameter
const s1 = test('number', 2);

// Expected 2 type arguments, but got 1
const s2 = test<MyType>('number', 2);

I need to call the function without the second generic parameter. How?

来源:https://stackoverflow.com/questions/62673801/how-can-i-call-a-generic-function-with-just-one-generic-parameter-when-the-secon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!