如何从作为参数传递的特定O
中推断出obj
?
export function pubsubs<O extends {[key: string]: Pubsub}>(
obj: O // extends infer U ? U : never
// ↑
// (failed attempt to infer)
): {
pub: Pubify<O>
sub: Subify<O>
} {
// ... generate pub and sub based on obj ...
return {pub, sub}
}
所需结果:
const {pub, sub} = pubsubs({ // ← (want to infer from this first arg)
// ↑
// (no generic)
userLogout: pubsub(),
userLoading: pubsub(),
userError: pubsub<(error: Error) => void>(),
userLogin: pubsub<(auth: LoginDetail) => void>(),
})
// but the typings fail to be inferred!
sub.userError(error => {})
// ↑
// (error type is 'any' )
没有推断的解决方法:
const input = {
userLogout: pubsub(),
userLoading: pubsub(),
userError: pubsub<(error: Error) => void>(),
userLogin: pubsub<(auth: LoginDetail) => void>(),
}
const {pub, sub} = pubsubs<typeof input>(input)
// ↑
// (should be inferred)
// typings are preserved
sub.userError(error => {})
// ↑
// (typescript knows)
如何推断类型并避免使用泛型类型参数?