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
}
}
})
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
}
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With