0

Typescript comes with a few nice type arithmetic operations like this one:

let target: ReturnType<typeof AcceptTerms>;

In this example AcceptTerms is a function that returns Operation<AcceptTermsParams, string>.

I'm wondering if it is possible to extract the generic type parameters and apply them to another type of a similar shape.

What I'm trying to achieve in practice is to generate a Permission object for all my Operations:

type Permission<I, O> {
    name: string;
    operationName: string;
    // ...
}

type Operation<I, O> = {
    name: string;
    // ...
};

My problem is that I don't have instances of Operations that I can use, only functions that return Operations (hence the ReturnType<typeof AcceptTerms>).

Right now this is how I create permissions for an Operation:

const allowViewAvailableBasketsForAll: Permission<void, Basket[]> = {
    name: "Allow view available baskets for all",
    operationName: VIEW_AVAILABLE_BASKETS_NAME,
    policies: [allowAllPolicy()],
};

But it would be nice to be able to do something like this:

export const withAllowAllFor = <??extract type params of operation somehow??>(name: string): Permission<I, O> => ({
    name: `Allow ${name} for all`,
    operationName: name,
    policies: [allowAllPolicy()],
});

So instead of supplying I and O by hand:

<I, O, T extends Operation<I, O>>

Can I somehow derive them from a type of Operation<I, O>?

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
  • 1
    Does this answer your question? [TypeScript: how to extract the generic parameter from a type?](https://stackoverflow.com/questions/44851268/typescript-how-to-extract-the-generic-parameter-from-a-type) – Blackhole Nov 06 '22 at 21:39
  • "This question does not show any research effort". The duplicate is literally the first link for the "extract generic type parameter typescript" search on Google. – Blackhole Nov 07 '22 at 08:01
  • > The duplicate is literally the first link for the "extract generic type parameter typescript" search on Google For me it is not, and I wasn't able to find that answer. – Adam Arold Nov 07 '22 at 08:49
  • So, is that link an answer? – Dimava Nov 07 '22 at 09:14
  • No, as it only handles single type parameters. – Adam Arold Nov 07 '22 at 11:25

0 Answers0