Highmastdon
Highmastdon

Reputation: 7530

Is it possible to create an alias for when a generic is of a certain type?

I want a type that takes a generic that extends an object of functions and 'nested' functions and "returns" an object where each function has a modified function signature.

So this

{ foo: (a) => (b) => ({}), nested: { bar: (a) => (b) => ({}) } }

becomes this

{ foo: (a) => ({}), nested: { bar: (a) => ({}) } }

I've tried to type it like this:

type Convertor<
  T extends { [key: string]: NestedMap<Function> | Function }
> = { [P in keyof T]: Converting<T[P]> }

This doesn't work since Converting<T[P]> should only happen when it's a function. I.e. for foo and nested.bar but not for nested, since that's an object.

How to type this properly?

Upvotes: 1

Views: 160

Answers (1)

cevek
cevek

Reputation: 862

Until the conditional types will have landed you can use crazy solution from https://github.com/Microsoft/TypeScript/issues/12424#issuecomment-356685955

type False = '0';
type True = '1';
type If<C extends True | False, Then, Else> = { '0': Else, '1': Then }[C];

type Diff<T extends string, U extends string> = (
    { [P in T]: P } & { [P in U]: never } & { [x: string]: never }
)[T];

type X<T> = Diff<keyof T, keyof Object>

type Is<T, U> = (Record<X<T & U>, False> & Record<any, True>)[Diff<X<T>, X<U>>]

type DeepFun<T> = {
    [P in keyof T]: If<Is<Function & T[P], Function>, ()=>{}, DeepFun<T[P]>>
}

type MyType = { foo: (a:any) => (b:any) => ({}), nested: { bar: (a:any) => (b:any) => ({}) } }
type NewType = DeepFun<MyType>;
var d:NewType; // type is {foo: ()=>{}, nested: {bar: ()=>{}}}

Upvotes: 1

Related Questions