I\'m trying to type a fetcher component API that I\'m working on. The idea is quite simple, you give it a fetcher
(promise returning function) and a param
This is possible in TypeScript 3.0.
To answer the question, I used ArgumentTypes<F>
from
this answer to: How to get argument types from function in Typescript.
Here's how:
Demo on TypeScript playground
type ArgumentTypes<F extends Function> =
F extends (...args: infer A) => any ? A : never;
type Props<F extends Function,
Params = ArgumentTypes<F>> =
Params extends { length: 0 } ?
{
fetcher: F;
} : {
fetcher: F;
params: Params
};
function runTest<F extends Function>(props: Props<F>) { }
function test0() { }
function test1(one: number) { }
runTest({
fetcher: test0
// , params: [] // Error
});
runTest({
fetcher: test1
// Comment it,
// or replace it with invalid args
// and see error
, params: [1]
});