如何推断通用参数的属性类型并映射到其他类型

时间:2020-11-12 17:44:55

标签: typescript

testFunc1使用SomeMapper并获取正确的通用参数。

在下面的testFunc2中,我尝试使用映射类型作为函数参数,但是由于某些原因,SomeMapper获取了错误的通用参数。

如何获取{ name: 'match' }作为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
    }
  }
})

2 个答案:

答案 0 :(得分:1)

我相信您可以这样做

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
    }
  }
})

答案 1 :(得分:0)

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
    }
  }
})

我试过了,它没有任何错误。如果这行得通,那么我为您感到高兴。