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
}
}
})
Run Code Online (Sandbox Code Playgroud)
小智 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
}
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
160 次 |
| 最近记录: |