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
}
}
})
最佳答案
我相信你可以这样做
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
}
}
})
关于typescript - 如何推断泛型参数的属性类型并映射到另一种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64809051/