Reputation: 732
I generated a typescript-node client of an API and I have something like this:
export declare class Api {
getUser(username: string, email: string, idType: '1298' | '2309' | '7801')
}
I want to get the type of the third parameter in order to not have to recreate a type '1298' | '2309' | '7801' in my application.
I managed to make it work by doing:
type idType = Parameters<Api['getUser']>[2];
I'm not really satisfied by this solution, I would like to use key 'idType' and not his parameter's position.
How can I do this ?
Thanks.
Upvotes: 2
Views: 220
Reputation: 20132
What you are using is the right way. My answer will contain some playing around in order to achieve some better readability of such construct. Consider this as just an alternative solution.
function getUser(username: string, email: string, idType: '1298' | '2309' | '7801') { }
// utility types in order to achieve the goal
type ArgName = 'first' | 'second' | 'third'
type ArgNum<T extends ArgName> =
T extends 'first' ? 0 :
T extends 'second' ? 1 :
T extends 'third' ? 2 :
0
type ArgumentType
<F extends (...a: any) => any, N extends ArgName> =
Parameters<F>[ArgNum<N>]
type A = ArgumentType<typeof getUser, 'third'>; // '1298' | '2309' | '7801'
As you can see the main difference is that we are using some readable keys instead of numbers. For functions with bigger arity we can extend the keys.
For your particular case the usage would look like:
type IdType = ArgumentType<Api['getUser'], 'third'>; // '1298' | '2309' | '7801'
Upvotes: 1
Reputation: 1776
export declare class Api {
getUser(username: string, email: string, idType: IdType)
}
export type IdType = '1298' | '2309' | '7801';
Upvotes: 0