[英]Complex generic type constraint
I'm trying to write a function getDocument
which would do the following:我正在尝试编写一个 function
getDocument
它将执行以下操作:
interface DocumentReference<T> {
get(): Promise<T>;
}
interface ParentA {
foo: DocumentReference<User>;
}
interface ParentB {
bar: DocumentReference<Company>;
}
// getDocument<ParentType>(parent: ParentType, fieldName: keyof ParentType): Promise<???>
getDocument(parentA, 'foo') // return a Promise<User>
getDocument(parentB, 'bar') // return a Promise<Company>
I've been trying many different combinations of generic signatures for getDocument
but can't figure out how to restrict fieldName
so that it corresponds to a field value of type DocumentReference
.我一直在为
getDocument
尝试许多不同的通用签名组合,但无法弄清楚如何限制fieldName
以使其对应于DocumentReference
类型的字段值。 I don't know how to extract the generic parameter of DocumentReference<T>
into the return type either.我也不知道如何将
DocumentReference<T>
的泛型参数提取到返回类型中。
Is this doable in typescript?这在 typescript 中可行吗? If yes, any pointers?
如果是,任何指针?
interface User {
a: number
}
interface Company {
b: string
}
interface DocumentReference<T> {
get(): Promise<T>;
}
interface ParentA {
foo: DocumentReference<User>;
}
interface ParentB {
bar: DocumentReference<Company>;
}
declare function getDocument<T extends ParentA | ParentB, K extends keyof T>(value: T, key: K): Promise<T[K] extends DocumentReference<infer R> ? R : never>;
declare const parentA: ParentA
declare const parentB: ParentB
getDocument(parentA,'foo')
getDocument(parentB,'bar')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.