Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 基于鉴别器的子集获取受鉴别器并集的子集_Typescript - Fatal编程技术网

Typescript 基于鉴别器的子集获取受鉴别器并集的子集

Typescript 基于鉴别器的子集获取受鉴别器并集的子集,typescript,Typescript,打字问题: 给定一个有区别的联合类型 interface A { discriminator: "A"; data: string; } interface B { discriminator: "B"; data: string; } interface C { discriminator: "C"; num: number; } type U = A | B | C; type

打字问题:

给定一个有区别的联合类型

interface A {
    discriminator: "A";
    data: string;
}

interface B {
    discriminator: "B";
    data: string;
}

interface C {
    discriminator: "C";
    num: number;
}

type U = A | B | C;
type Discriminator = U["discriminator"];

type AorB = SubsetOfU<"A"|"B">;

const f = (d:AorB) => d.data; // Should work

接口A{
鉴别器:“A”;
数据:字符串;
}
接口B{
鉴别器:“B”;
数据:字符串;
}
接口C{
鉴别器:“C”;
num:数字;
}
U型=A | B | C;
类型鉴别器=U[“鉴别器”];
AorB型=亚豆腐;
常数f=(d:AorB)=>d.data;//应该有用
如何编写
subsetof
来提取联合类型的子集

当然,我不是在这里解决具体的案例(只是
A | B
),而是一个更复杂的场景


type subsetof=?????

已定义了
Extract
预定义类型并执行您想要的操作:

type U = A | B | C;
type Discriminator = U["discriminator"];

type AorB = Extract<U, { discriminator: "A" | "B" }>;

const f = (d:AorB) => d.data;
U型=A | B | C; 类型鉴别器=U[“鉴别器”]; AorB型=提取物; 常数f=(d:AorB)=>d.data;

原来我已经有了这样做的代码,所以当我再次忘记它时,我可以在这里找到答案

这就是解决方案:

type SubsetOfU<T, K> = T extends { discriminator: K }
  ? T
  : never;
type subsetof=T扩展{discriminator:K}
? T
:从不;

如果您已经定义了子类型的类型,那么实际上不需要使用
{descriminator:'A'|'B'}
,在您的情况下,
A
B
&
c

U型=A | B | C 类型AorB=提取 常数f=(d:AorB)=>d.data
这是否回答了您的问题?