typescript - 打字稿不能正确推断类型
问题描述
class A {
readonly is_prop: boolean;
constructor(is_prop: boolean) {
this.is_prop = is_prop;
}
}
class B {
readonly my_prop: boolean;
constructor(my_prop: boolean) {
this.my_prop = my_prop;
}
}
type A1 = A & {is_prop: true};
type A2 = A & {is_prop: false};
type C = A1 | A2 | B;
const a: A = new A(true);
const b: A = new A(false);
const c: B = new B(true);
const e: A1 | null = a.is_prop ? a : null;
在上面的例子中,为什么赋值e
给错误?为什么 TS 不推断这is_prop
将是真的
解决方案
错误是因为a
是类型A
:
const a: A = new A(true);
在三元中,您检查is_prop
is true
,但变量a
仍然是 类型A
。该属性已缩小到true
,但a
没有更改类型。例如,根据您的缩小范围,此代码将是有效的:
const trueVal: true | null = a.is_prop ? a.is_prop : null
如果您希望能够缩小 的类型a
,则需要通过声明它是联合来说明它可以是多种类型之一:
const a: A1|A2 = new A(true);
有更多选择的游乐场。
推荐阅读
- xaml - 为什么我的 Xamarin.Forms 控件在 StackLayout 中重叠?
- python - 尝试创建表单
- javascript - 使用 HTML / CSS / JavaScript 隐藏 YouTube 视频控件(标题、稍后观看、分享)
- javascript - 如何在辅助函数/mixin 中获取 Vue 模块
- python - 将多维 pytorch 张量拆分为“n”个较小的张量
- docker - Docker 容器无法启动 NestJs 应用程序
- javascript - 只使 HTML 链接在一定的点击量下工作?
- python - 如何让不和谐的机器人在python中离开语音通道
- javascript - 使用 JS 和按钮更改 html 中的背景
- flutter - 如何在 Flutter 的 SearchDelegate 中使用 SliverAppBar 隐藏 Scroll 上的 AppBar