Определите тип generi c функции generi c после использования typeof - PullRequest
0 голосов
/ 25 мая 2020

Посмотрите на следующий пример:

function test<T>(a: T[]) {return a};
type testReturnType = ReturnType<typeof test> // typescript infers type unknown[]

Есть ли способ параметризовать generi c type T of testType, чтобы я мог выбрать T? Я хочу sh сделать что-то вроде:

type testReturnType<A> = ReturnType<typeof test<A>>

Где машинописный текст выведет тип testReturnType<A> как A[], и поэтому я мог бы сделать что-то вроде:

function anotherFunction(b: testReturnType<number>) {..}

Это как-то возможно?

1 Ответ

0 голосов
/ 25 мая 2020

Да, к сожалению, нет способа сделать это на чистом TypeScript: (

Однако вы можете обойти свою проблему следующим образом:

// First let's create a type signature for the test function
type TestFunction<T> = (params: T[]) => T[];

// Then the function itself
function test<T>(a: T[]) {
  return a;
}

// At this point you could say okay, I will just always make sure that test()
// is of type TestFunction. OR: You can bind them together!
// Since you cannot 'assign' a type to a function in TypeScript
// and you can't have generic const either you have to use a little trick:
const assertTest = <T>(): TestFunction<T> => test;

// The assertTest will just make sure that the signature of test()
// and the TestFunction type match. (you don't actually need to call it anywhere in your code)

// Then you can create your return type helper easily:
type TestReturnType<T> = ReturnType<TestFunction<T>>;

Затем вы можете попробовать делать более глупые вещи с помощью своего TestFunction введите и убедитесь, что код все еще работает:

type TestFunction<T> = (params: T[]) => T extends string ? number : T[];

// ...

type A = TestReturnType<string>; // A will be number
type B = TestReturnType<{}>; // A will be {}[]

Надеюсь, что это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...