作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一些类型定义,如下所示。
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[]
.
T
有效载荷是
PayloadA
,应该也能缩小
entries: T[]
至
entries: PayloadB[]
.我知道我可以进行类型转换,例如:
function f(interpretation: TPayloadInterpretation) {
if (interpretation.payload.type === 'B') {
const payloadBInterpretation = interpretation as PayloadInterpretation<PayloadB>;
...
}
}
但我的问题是有没有其他方法可以做到这一点?
最佳答案
当您检查 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/
我是一名优秀的程序员,十分优秀!