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
}
}
})
答案 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
}
}
})
我试过了,它没有任何错误。如果这行得通,那么我为您感到高兴。