gpt4 book ai didi

javascript - 基于区分联合缩小 typescript 泛型类型

转载 作者:行者123 更新时间:2023-12-04 07:17:01 25 4
gpt4 key购买 nike

我有一些类型定义,如下所示。

type PayloadType = 'A' | 'B';

interface Payload<T extends PayloadType> {
type: T;
}

interface PayloadA extends Payload<'A'> {
state: string
}

interface PayloadB extends Payload<'B'> {
serialNumber: string;
}

type TPayload = PayloadA | PayloadB;


type PayloadInterpretation<T extends TPayload> = {
payload: T;
entries: T[]; // This property is only for demonstration purpose
};

type TPayloadInterpretation = PayloadInterpretation<PayloadA> | PayloadInterpretation<PayloadB>;

function f(interpretation: TPayloadInterpretation) {
if (interpretation.payload.type === 'B') {
const payload = interpretation.payload; // payload is of type PayloadB
const entries = interpretation.entries; // entries is of type PayloadA[] | PayloadB[]
}
}

评论表明,即使有效载荷的类型也可以正确缩小到 PayloadB基于歧视联合,但类型 T[]entries还在 PayloadA[] | PayloadB[] .
我在想 typescript 是否知道类型 T有效载荷是 PayloadA ,应该也能缩小 entries: T[]entries: PayloadB[] .我知道我可以进行类型转换,例如:
function f(interpretation: TPayloadInterpretation) {
if (interpretation.payload.type === 'B') {
const payloadBInterpretation = interpretation as PayloadInterpretation<PayloadB>;
...
}
}
但我的问题是有没有其他方法可以做到这一点?
代码是 here在 typescript 游乐场。
谢谢!

最佳答案

当您检查 interpretation.payload.type 时,你只是缩小了interpretation.payload目的。您实际上并没有采取任何措施来缩小范围 interpretation.entries .
换句话说, typescript 不知道 interpretation.entries缩小时也可以缩小interpretation.payload .
如果您希望两者都缩小,则需要在 PayloadInterpretation 中使用另一个鉴别器类型:

// ...

type PayloadInterpretation<T extends TPayload> = {
type: T['type']; // the new discriminator for the whole PayloadInterpretation
payload: T;
entries: T[];
};

// ...

function f(interpretation: TPayloadInterpretation) {
if (interpretation.type === 'B') { // narrowing the whole interpretation instead of only interpretation.payload
const payload = interpretation.payload; // payload is of type PayloadB
const entries = interpretation.entries; // entries is of type PayloadB[]
}
}

关于javascript - 基于区分联合缩小 typescript 泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68700574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com