【发布时间】:2022-07-29 09:19:05
【问题描述】:
我对根据单个字段的类型缩小类型感兴趣。但是,TypeScript 似乎没有像在 if 语句中直接使用原始运算符那样使用类型谓词来缩小类型中其他参数的类型。有什么办法可以让类型缩小在这里正常工作吗?
export function isTrue(input: boolean | undefined | null): input is true {
return input === true;
}
type Refine =
| {
b: true;
c: 'bIsTrue';
}
| {
b: undefined;
c: 'bIsUndefined';
}
| {
b: false;
c: 'bIsFalse';
};
export function example() {
const example = (null as unknown) as Refine;
if (example.b === true) {
example.b; // Type is: true
example.c; // Type is: 'bIsTrue'
}
if (isTrue(example.b)) {
example.b; // Type is: true
example.c; // Type is: 'bIsTrue' | 'bIsUndefined' | 'bIsFalse'
}
}
【问题讨论】:
标签: typescript