Да, к сожалению, нет способа сделать это на чистом 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 {}[]
Надеюсь, что это поможет!