Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to infer property type of generic parameter and map to another type

Tags:

typescript

testFunc1 is using SomeMapper and getting the correct generic parameter.

In testFunc2 below I try to use a mapped type as function argument, but for some reason the SomeMapper is getting the wrong generic parameter.

How can I get { name: 'match' } as function argument for listener?

type SomeMapper<T> = { [K in keyof T]: 'A' extends T[K] ? 'match' : 'no-match' }

function testFunc1<T extends Record<string, { params: Record<string, string> }>>(
  args: T & { [K in keyof T]: { listener: SomeMapper<T[K]['params']> } }
) {}

const test1 = testFunc1({
  someEvent: {
    params: { name: 'A' as const },
    listener: { name: 'match' } // type mapping with SomeMapper works!
  }
})

function testFunc2<T extends Record<string, { params: Record<string, string> }>>(
  args: T & { [K in keyof T]: { listener: (args: SomeMapper<T[K]['params']>) => unknown } }
) {}

const test2 = testFunc2({
  someEvent: {
    params: { name: 'A' as const },
    listener: (args /* args = SomeMapper<Record<string, string>> */) => {
      // 'args' should be { name: 'match' }

      return
    }
  }
})
like image 624
Jacob Avatar asked Nov 12 '20 17:11

Jacob


1 Answers

I believe you can do it like this

type SomeMapper<T> = { [K in keyof T]: 'A' extends T[K] ? 'match' : 'no-match' }

type ListenerDecl<T> = {
  params: T;
  listener: (args: SomeMapper<T>) => unknown
}

function testFunc2<T extends Record<string, unknown>>(
  args: { [K in keyof T]: ListenerDecl<T[K]> }
) { }


const test2 = testFunc2({
  someEvent: {
    params: { name: 'A' as const },
    listener: (args) => {
      // 'args' should be { name: 'match' }
      return
    }
  }
})
like image 173
Artyom Smirnov Avatar answered Nov 15 '22 09:11

Artyom Smirnov