[英]Infer return type from generic types
我想根据输入参数推断特定情况下的类型以获取Box<T>
或T
,但我最终得到Box<unknown>
和 unknown 。 我认为这是因为我使用了W extends Wrap<T>
,但我不知道如何更好地表达这一点。
请参阅此代码示例,hover over boxResult
和noBoxResult
以查看推断的类型对我来说并不理想:
// Type definitions
interface ComplicatedDataContainer<T> {
// contains many Ts in some complicated fashion
}
interface WrapA<T> {
v: ComplicatedDataContainer<T>,
p: "Box"
}
interface WrapB<T> {
v: ComplicatedDataContainer<T>,
p: "NoBox"
}
type Wrap<T> = WrapA<T> | WrapB<T>;
type Box<T> = {
t: T
}
type SelectThing = <T, W extends Wrap<T>>(id: string, w: W) => W extends {p: "Box"} ? Box<T> : T
// Usage example
const wBox: WrapA<string> = {
v: "",
p: "Box"
}
const wNoBox: WrapB<string> = {
v: "",
p: "NoBox"
}
const selector: SelectThing = (id: string, w: Wrap<any>) => {throw new Error()}; // dont care about runtime behavior here, real impls are way more complicated
// I want the type of this to be Box<string>, but it is Box<unknown>
const boxResult = selector("", wBox);
// I want the type of this to be string, but it is unknown
const noBoxResult = selector("", wNoBox);
您可以在此处运行此示例。
问题是T
没有推理站点,因此它默认为unknown
。 实际上,这里不需要单独的类型参数T
,因为它可以从类型参数W
派生。 下面的Unwrap
类型执行此推导。
type Unwrap<W extends Wrap<any>> = W extends Wrap<infer T> ? T : never
type SelectThing =
<W extends Wrap<any>>(id: string, w: W) => W extends {p: "Box"} ? Box<Unwrap<W>> : Unwrap<W>
请注意,我必须在示例中填写ComplicatedDataContainer
,以便它以某种方式依赖于T
,以避免意外的结构等价。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.