gpt4 book ai didi

typescript - 如何推断泛型参数的属性类型并映射到另一种类型

转载 作者:行者123 更新时间:2023-12-03 09:38:26 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com