[英]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.